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