summaryrefslogtreecommitdiff
path: root/src/stdio/popen.c
diff options
context:
space:
mode:
authorRich Felker <dalias@aerifal.cx>2011-02-12 00:22:29 -0500
committerRich Felker <dalias@aerifal.cx>2011-02-12 00:22:29 -0500
commit0b44a0315b47dd8eced9f3b7f31580cf14bbfc01 (patch)
tree6eaef0d8a720fa3da580de87b647fff796fe80b3 /src/stdio/popen.c
downloadmusl-0b44a0315b47dd8eced9f3b7f31580cf14bbfc01.tar.gz
initial check-in, version 0.5.0v0.5.0
Diffstat (limited to 'src/stdio/popen.c')
-rw-r--r--src/stdio/popen.c43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/stdio/popen.c b/src/stdio/popen.c
new file mode 100644
index 00000000..1d33e9d6
--- /dev/null
+++ b/src/stdio/popen.c
@@ -0,0 +1,43 @@
+#include "stdio_impl.h"
+
+FILE *popen(const char *cmd, const char *mode)
+{
+ int p[2];
+ int op;
+ pid_t pid;
+ FILE *f;
+ const char *modes = "rw", *mi = strchr(modes, *mode);
+
+ if (mi) {
+ op = mi-modes;
+ } else {
+ errno = EINVAL;
+ return 0;
+ }
+
+ if (pipe(p)) return NULL;
+ f = fdopen(p[op], mode);
+ if (!f) {
+ close(p[0]);
+ close(p[1]);
+ return NULL;
+ }
+
+ pid = fork();
+ switch (pid) {
+ case -1:
+ fclose(f);
+ close(p[0]);
+ close(p[1]);
+ return NULL;
+ case 0:
+ dup2(p[1-op], 1-op);
+ close(p[0]);
+ close(p[1]);
+ execl("/bin/sh", "sh", "-c", cmd, (char *)0);
+ _exit(127);
+ }
+ close(p[1-op]);
+ f->pipe_pid = pid;
+ return f;
+}