popen.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <fcntl.h>
  2. #include "stdio_impl.h"
  3. #include "pthread_impl.h"
  4. #include "syscall.h"
  5. static void dummy_0()
  6. {
  7. }
  8. weak_alias(dummy_0, __acquire_ptc);
  9. weak_alias(dummy_0, __release_ptc);
  10. pid_t __vfork(void);
  11. FILE *popen(const char *cmd, const char *mode)
  12. {
  13. int p[2], op, i;
  14. pid_t pid;
  15. FILE *f;
  16. sigset_t old;
  17. const char *modes = "rw", *mi = strchr(modes, *mode);
  18. if (mi) {
  19. op = mi-modes;
  20. } else {
  21. errno = EINVAL;
  22. return 0;
  23. }
  24. if (pipe2(p, O_CLOEXEC)) return NULL;
  25. f = fdopen(p[op], mode);
  26. if (!f) {
  27. __syscall(SYS_close, p[0]);
  28. __syscall(SYS_close, p[1]);
  29. return NULL;
  30. }
  31. sigprocmask(SIG_BLOCK, SIGALL_SET, &old);
  32. __acquire_ptc();
  33. pid = __vfork();
  34. if (pid) {
  35. __release_ptc();
  36. __syscall(SYS_close, p[1-op]);
  37. sigprocmask(SIG_BLOCK, SIGALL_SET, &old);
  38. if (pid < 0) {
  39. fclose(f);
  40. return 0;
  41. }
  42. f->pipe_pid = pid;
  43. return f;
  44. }
  45. /* See notes in system.c for why this is needed. */
  46. for (i=1; i<=8*__SYSCALL_SSLEN; i++) {
  47. struct sigaction sa;
  48. __libc_sigaction(i, 0, &sa);
  49. if (sa.sa_handler!=SIG_IGN && sa.sa_handler!=SIG_DFL) {
  50. sa.sa_handler = SIG_DFL;
  51. __libc_sigaction(i, &sa, 0);
  52. }
  53. }
  54. if (dup2(p[1-op], 1-op) < 0) _exit(127);
  55. fcntl(1-op, F_SETFD, 0);
  56. if (p[0] != 1-op) __syscall(SYS_close, p[0]);
  57. if (p[1] != 1-op) __syscall(SYS_close, p[1]);
  58. sigprocmask(SIG_SETMASK, &old, 0);
  59. execl("/bin/sh", "sh", "-c", cmd, (char *)0);
  60. _exit(127);
  61. }