1
0

sym_script.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. /*--------------------------------------------------------- */
  21. CLISH_PLUGIN_OSYM(clish_script)
  22. {
  23. clish_shell_t *this = clish_context__get_shell(clish_context);
  24. const clish_action_t *action = clish_context__get_action(clish_context);
  25. const char *shebang = NULL;
  26. pid_t cpid = -1;
  27. int res;
  28. const char *fifo_name;
  29. FILE *wpipe;
  30. char *command = NULL;
  31. assert(this);
  32. if (!script) /* Nothing to do */
  33. return 0;
  34. /* Find out shebang */
  35. if (action)
  36. shebang = clish_action__get_shebang(action);
  37. if (!shebang)
  38. shebang = clish_shell__get_default_shebang(this);
  39. assert(shebang);
  40. #ifdef DEBUG
  41. fprintf(stderr, "SHEBANG: #!%s\n", shebang);
  42. fprintf(stderr, "SCRIPT: %s\n", script);
  43. #endif /* DEBUG */
  44. /* Get FIFO */
  45. fifo_name = clish_shell__get_fifo(this);
  46. if (!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. return -1;
  57. }
  58. /* Child: write to FIFO */
  59. if (cpid == 0) {
  60. wpipe = fopen(fifo_name, "w");
  61. if (!wpipe)
  62. _exit(-1);
  63. fwrite(script, strlen(script), 1, wpipe);
  64. fclose(wpipe);
  65. _exit(0);
  66. }
  67. /* Parent */
  68. /* Prepare command */
  69. lub_string_cat(&command, shebang);
  70. lub_string_cat(&command, " ");
  71. lub_string_cat(&command, fifo_name);
  72. res = system(command);
  73. /* Wait for the writing process */
  74. kill(cpid, SIGTERM);
  75. waitpid(cpid, NULL, 0);
  76. lub_string_free(command);
  77. #ifdef DEBUG
  78. fprintf(stderr, "RETCODE: %d\n", WEXITSTATUS(res));
  79. #endif /* DEBUG */
  80. return WEXITSTATUS(res);
  81. }