remove spurious lock in popen
[musl.git] / src / stdio / popen.c
blob19bbe7cfb1aa950936008ce4a99246456531fff6
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"
9 extern char **__environ;
11 FILE *popen(const char *cmd, const char *mode)
13 int p[2], op, e;
14 pid_t pid;
15 FILE *f;
16 posix_spawn_file_actions_t fa;
18 if (*mode == 'r') {
19 op = 0;
20 } else if (*mode == 'w') {
21 op = 1;
22 } else {
23 errno = EINVAL;
24 return 0;
27 if (pipe2(p, O_CLOEXEC)) return NULL;
28 f = fdopen(p[op], mode);
29 if (!f) {
30 __syscall(SYS_close, p[0]);
31 __syscall(SYS_close, p[1]);
32 return NULL;
35 e = ENOMEM;
36 if (!posix_spawn_file_actions_init(&fa)) {
37 if (!posix_spawn_file_actions_adddup2(&fa, p[1-op], 1-op)) {
38 if (!(e = posix_spawn(&pid, "/bin/sh", &fa, 0,
39 (char *[]){ "sh", "-c", (char *)cmd, 0 }, __environ))) {
40 posix_spawn_file_actions_destroy(&fa);
41 f->pipe_pid = pid;
42 if (!strchr(mode, 'e'))
43 fcntl(p[op], F_SETFD, 0);
44 __syscall(SYS_close, p[1-op]);
45 return f;
48 posix_spawn_file_actions_destroy(&fa);
50 fclose(f);
51 __syscall(SYS_close, p[1-op]);
53 errno = e;
54 return 0;