process.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2007 - 2021, Alan Antonuk and the rabbitmq-c contributors.
  2. // SPDX-License-Identifier: mit
  3. #include <errno.h>
  4. #include <spawn.h>
  5. #include <sys/wait.h>
  6. #include <unistd.h>
  7. #include "common.h"
  8. #include "process.h"
  9. extern char **environ;
  10. void pipeline(const char *const *argv, struct pipeline *pl) {
  11. posix_spawn_file_actions_t file_acts;
  12. int pipefds[2];
  13. if (pipe(pipefds)) {
  14. die_errno(errno, "pipe");
  15. }
  16. die_errno(posix_spawn_file_actions_init(&file_acts),
  17. "posix_spawn_file_actions_init");
  18. die_errno(posix_spawn_file_actions_adddup2(&file_acts, pipefds[0], 0),
  19. "posix_spawn_file_actions_adddup2");
  20. die_errno(posix_spawn_file_actions_addclose(&file_acts, pipefds[0]),
  21. "posix_spawn_file_actions_addclose");
  22. die_errno(posix_spawn_file_actions_addclose(&file_acts, pipefds[1]),
  23. "posix_spawn_file_actions_addclose");
  24. die_errno(posix_spawnp(&pl->pid, argv[0], &file_acts, NULL,
  25. (char *const *)argv, environ),
  26. "posix_spawnp: %s", argv[0]);
  27. die_errno(posix_spawn_file_actions_destroy(&file_acts),
  28. "posix_spawn_file_actions_destroy");
  29. if (close(pipefds[0])) {
  30. die_errno(errno, "close");
  31. }
  32. pl->infd = pipefds[1];
  33. }
  34. int finish_pipeline(struct pipeline *pl) {
  35. int status;
  36. if (close(pl->infd)) {
  37. die_errno(errno, "close");
  38. }
  39. if (waitpid(pl->pid, &status, 0) < 0) {
  40. die_errno(errno, "waitpid");
  41. }
  42. return WIFEXITED(status) && WEXITSTATUS(status) == 0;
  43. }