runscript.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. // TODO: Not nescessary
  6. #include <stdio.h>
  7. #include <string>
  8. #include <vector>
  9. #include "common.h"
  10. extern "C" {
  11. int run_script(std::string arg0, std::vector<std::string> env)
  12. {
  13. /* Convert the vector containing environment variables to the format
  14. * expected by execle(). */
  15. char const* envp[env.size() + 1];
  16. for (int i = 0; i < env.size(); ++i) {
  17. envp[i] = env[i].data();
  18. }
  19. envp[env.size()] = (char const*) NULL;
  20. /* fork() & execle() */
  21. int ret, wstatus, exitcode;
  22. pid_t pid;
  23. pid = fork();
  24. if (pid == -1) {
  25. // TODO: logging, errno is usable
  26. fprintf(stderr, "Error during fork()\n");
  27. return -1;
  28. }
  29. if (pid == 0) {
  30. /* Child process */
  31. ret = execle(script_path.data(), script_name.data(), arg0.data(), (char *)NULL, envp);
  32. // TODO: logging, errno is usable
  33. fprintf(stderr, "Error during execle() in child\n");
  34. exit(EXIT_FAILURE);
  35. } else {
  36. /* Parent process */
  37. fprintf(stderr, "Waiting for script to return...\n");
  38. ret = wait(&wstatus);
  39. if (ret == -1) {
  40. // TODO: logging, errno is usable
  41. fprintf(stderr, "waitpid() failure\n");
  42. return -1;
  43. }
  44. /* Get exit code */
  45. if (WIFEXITED(wstatus))
  46. exitcode = WEXITSTATUS(wstatus);
  47. else
  48. /* By default, assume everything worked well */
  49. exitcode = 0;
  50. return exitcode;
  51. }
  52. }
  53. } // end extern "C"