1 
2 #include <stdio.h>
3 
4 
popen(command,rw)5 FILE * popen(command, rw)
6 char * command;
7 char * rw;
8 {
9    int pipe_fd[2];
10    int pid, reading;
11 
12    if( pipe(pipe_fd) < 0 ) return NULL;
13    reading = (rw[0] == 'r');
14 
15    pid = vfork();
16    if( pid < 0 ) { close(pipe_fd[0]); close(pipe_fd[1]); return NULL; }
17    if( pid == 0 )
18    {
19       close(pipe_fd[!reading]);
20       close(reading);
21       if( pipe_fd[reading] != reading )
22       {
23 	 dup2(pipe_fd[reading], reading);
24          close(pipe_fd[reading]);
25       }
26 
27       execl("/bin/sh", "sh", "-c", command, (char*)0);
28       _exit(255);
29    }
30 
31    close(pipe_fd[reading]);
32    return fdopen(pipe_fd[!reading], rw);
33 }
34 
pclose(fd)35 int pclose(fd)
36 FILE *fd;
37 {
38    int waitstat;
39    if( fclose(fd) != 0 ) return EOF;
40    wait(&waitstat);
41 }
42 
43