1
0

popen.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. FLOCK(f);
  31. /* If the child's end of the pipe happens to already be on the final
  32. * fd number to which it will be assigned (either 0 or 1), it must
  33. * be moved to a different fd. Otherwise, there is no safe way to
  34. * remove the close-on-exec flag in the child without also creating
  35. * a file descriptor leak race condition in the parent. */
  36. if (p[1-op] == 1-op) {
  37. int tmp = fcntl(1-op, F_DUPFD_CLOEXEC, 0);
  38. if (tmp < 0) {
  39. e = errno;
  40. goto fail;
  41. }
  42. __syscall(SYS_close, p[1-op]);
  43. p[1-op] = tmp;
  44. }
  45. e = ENOMEM;
  46. if (!posix_spawn_file_actions_init(&fa)) {
  47. if (!posix_spawn_file_actions_adddup2(&fa, p[1-op], 1-op)) {
  48. if (!(e = posix_spawn(&pid, "/bin/sh", &fa, 0,
  49. (char *[]){ "sh", "-c", (char *)cmd, 0 }, __environ))) {
  50. posix_spawn_file_actions_destroy(&fa);
  51. f->pipe_pid = pid;
  52. if (!strchr(mode, 'e'))
  53. fcntl(p[op], F_SETFD, 0);
  54. __syscall(SYS_close, p[1-op]);
  55. FUNLOCK(f);
  56. return f;
  57. }
  58. }
  59. posix_spawn_file_actions_destroy(&fa);
  60. }
  61. fail:
  62. fclose(f);
  63. __syscall(SYS_close, p[1-op]);
  64. errno = e;
  65. return 0;
  66. }