/* EpOpen.c -- Extended popen command Returns streams for read AND write instead of just one or the other. Tested under Debian 1.3.1r6, libc5.4.33, Linux 2.0.33 Copyright (C) 1998, 2000 Piotr F. Mitros This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Questions? Comments? Contact: pmitros@mit.edu. After 2001, hopefully pmitros@alum.mit.edu :) */ /* Extended popen -- open a command for read and write */ #include #include #include #include int epopen(FILE**fin, FILE**fout, const char *command) { int inpipe[2], outpipe[2]; int pid; if(pipe(inpipe)) return -1; if(pipe(outpipe)) return -1; /* Exit, since a failed fork can leave the system in a fscked up state */ if((pid = fork()) < 0) { perror("Fork"); exit(1); } perror("Should get here twice..."); /* The child process executes the command */ if(pid==0) { perror("Got here"); dup2(outpipe[1], 1); dup2(inpipe[0], 0); perror("Opened pipes"); execl("/bin/sh", "sh", "-c", command, 0); perror("Should not have got here"); _exit(127); } perror("About to close"); close(inpipe[0]); close(outpipe[1]); perror("Closing"); *fin=fdopen(inpipe[1], "w"); *fout=fdopen(outpipe[0], "r"); } void main() { FILE *fin, *fout; int i; epopen(&fout, &fin, "grep 5"); for(i=0; i<100; i++) fprintf(fout, "%d\n", i); fclose(fout); while(!feof(fin)) { printf("Got here, %c", (fgetc(fin))); } }