popen.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <spawn.h>
  6. #include "stdio_impl.h"
  7. #include "syscall.h"
  8. extern char **__environ;
  9. FILE *popen(const char *cmd, const char *mode)
  10. {
  11. int p[2], op, e;
  12. pid_t pid;
  13. FILE *f;
  14. posix_spawn_file_actions_t fa;
  15. if (*mode == 'r') {
  16. op = 0;
  17. } else if (*mode == 'w') {
  18. op = 1;
  19. } else {
  20. errno = EINVAL;
  21. return 0;
  22. }
  23. if (pipe2(p, O_CLOEXEC)) return NULL;
  24. f = fdopen(p[op], mode);
  25. if (!f) {
  26. __syscall(SYS_close, p[0]);
  27. __syscall(SYS_close, p[1]);
  28. return NULL;
  29. }
  30. e = ENOMEM;
  31. if (!posix_spawn_file_actions_init(&fa)) {
  32. for (FILE *l = *__ofl_lock(); l; l=l->next)
  33. if (l->pipe_pid && posix_spawn_file_actions_addclose(&fa, l->fd))
  34. goto fail;
  35. if (!posix_spawn_file_actions_adddup2(&fa, p[1-op], 1-op)) {
  36. if (!(e = posix_spawn(&pid, "/bin/sh", &fa, 0,
  37. (char *[]){ "sh", "-c", (char *)cmd, 0 }, __environ))) {
  38. posix_spawn_file_actions_destroy(&fa);
  39. f->pipe_pid = pid;
  40. if (!strchr(mode, 'e'))
  41. fcntl(p[op], F_SETFD, 0);
  42. __syscall(SYS_close, p[1-op]);
  43. __ofl_unlock();
  44. return f;
  45. }
  46. }
  47. fail:
  48. __ofl_unlock();
  49. posix_spawn_file_actions_destroy(&fa);
  50. }
  51. fclose(f);
  52. __syscall(SYS_close, p[1-op]);
  53. errno = e;
  54. return 0;
  55. }