sym_script.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * sym_script.c
  3. *
  4. * Function to execute a shell script.
  5. */
  6. #include "private.h"
  7. #include "lub/string.h"
  8. #include "konf/buf.h"
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <unistd.h>
  12. #include <string.h>
  13. #include <assert.h>
  14. #include <signal.h>
  15. #include <sys/types.h>
  16. #include <sys/wait.h>
  17. #include <sys/types.h>
  18. #include <sys/stat.h>
  19. #include <fcntl.h>
  20. #include <limits.h>
  21. /*--------------------------------------------------------- */
  22. CLISH_PLUGIN_OSYM(clish_script)
  23. {
  24. clish_shell_t *this = clish_context__get_shell(clish_context);
  25. const clish_action_t *action = clish_context__get_action(clish_context);
  26. const char *shebang = NULL;
  27. pid_t cpid = -1;
  28. int res;
  29. char fifo_name[PATH_MAX];
  30. FILE *wpipe;
  31. char *command = NULL;
  32. assert(this);
  33. if (!script) /* Nothing to do */
  34. return 0;
  35. /* Find out shebang */
  36. if (action)
  37. shebang = clish_action__get_shebang(action);
  38. if (!shebang)
  39. shebang = clish_shell__get_default_shebang(this);
  40. assert(shebang);
  41. #ifdef DEBUG
  42. fprintf(stderr, "SHEBANG: #!%s\n", shebang);
  43. fprintf(stderr, "SCRIPT: %s\n", script);
  44. #endif /* DEBUG */
  45. /* Create FIFO */
  46. if (! clish_shell_mkfifo(this, fifo_name, sizeof(fifo_name))) {
  47. fprintf(stderr, "Error: Can't create temporary FIFO.\n"
  48. "Error: The ACTION will be not executed.\n");
  49. return -1;
  50. }
  51. /* Create process to write to FIFO */
  52. cpid = fork();
  53. if (cpid == -1) {
  54. fprintf(stderr, "Error: Can't fork the write process.\n"
  55. "Error: The ACTION will be not executed.\n");
  56. clish_shell_rmfifo(this, fifo_name);
  57. return -1;
  58. }
  59. /* Child: write to FIFO */
  60. if (cpid == 0) {
  61. wpipe = fopen(fifo_name, "w");
  62. if (!wpipe)
  63. _exit(-1);
  64. fwrite(script, strlen(script), 1, wpipe);
  65. fclose(wpipe);
  66. _exit(0);
  67. }
  68. /* Parent */
  69. /* Prepare command */
  70. lub_string_cat(&command, shebang);
  71. lub_string_cat(&command, " ");
  72. lub_string_cat(&command, fifo_name);
  73. res = system(command);
  74. /* Wait for the writing process */
  75. kill(cpid, SIGTERM);
  76. while (waitpid(cpid, NULL, 0) != cpid);
  77. /* Clean up */
  78. lub_string_free(command);
  79. clish_shell_rmfifo(this, fifo_name);
  80. #ifdef DEBUG
  81. fprintf(stderr, "RETCODE: %d\n", WEXITSTATUS(res));
  82. #endif /* DEBUG */
  83. return WEXITSTATUS(res);
  84. }