tst-posix_spawn.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <spawn.h>
  6. #include <sys/wait.h>
  7. extern char **environ;
  8. void run_cmd(char *cmd)
  9. {
  10. pid_t pid;
  11. posix_spawnattr_t attrs;
  12. posix_spawn_file_actions_t actions;
  13. sigset_t defsignals;
  14. char *argv[] = {"sh", "-c", cmd, NULL};
  15. int status;
  16. sigemptyset(&defsignals);
  17. sigaddset(&defsignals, SIGTERM);
  18. sigaddset(&defsignals, SIGCHLD);
  19. sigaddset(&defsignals, SIGPIPE);
  20. posix_spawnattr_init(&attrs);
  21. posix_spawnattr_setflags(&attrs, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGDEF);
  22. posix_spawnattr_setpgroup(&attrs, 0);
  23. posix_spawnattr_setsigdefault(&attrs, &defsignals);
  24. posix_spawn_file_actions_init(&actions);
  25. printf("Run command: %s\n", cmd);
  26. status = posix_spawn(&pid, "/bin/sh", &actions, &attrs, argv, environ);
  27. if (status == 0) {
  28. printf("Child pid: %i\n", pid);
  29. if (waitpid(pid, &status, 0) != -1) {
  30. printf("Child exited with status %i\n", status);
  31. } else {
  32. perror("waitpid");
  33. }
  34. } else {
  35. printf("posix_spawn: %s\n", strerror(status));
  36. }
  37. }
  38. int main(int argc, char* argv[])
  39. {
  40. run_cmd(argv[1]);
  41. return 0;
  42. }