Why does popen () work only once?

When I run the program below on my Mac (OS / X 10.6.4), I get the following output:

$ ./a.out Read 66 lines of output from /bin/ps Read 0 lines of output from /bin/ps Read 0 lines of output from /bin/ps Read 0 lines of output from /bin/ps Read 0 lines of output from /bin/ps 

Why is it that popen () only reads the data on the first call, and subsequent skips do not return the output?

 #include <stdio.h> int main(int argc, char ** argv) { int i; for (i=0; i<5; i++) { FILE * psAux = popen("/bin/ps ax", "r"); if (psAux) { char buf[1024]; int c = 0; while(fgets(buf, sizeof(buf), psAux)) c++; printf("Read %i lines of output from /bin/ps\n", c); fclose(psAux); } else printf("Error, popen() failed!\n"); sleep(1); } } 
+4
source share
2 answers

You should use pclose instead of fclose . (Verified and verified.)

fclose does not reset the state of the pipe, as it is intended to close files, not pipes. pclose will close the tube correctly so you can open it again.

+6
source

Take a look here to see why fclose and pclose differ and how.

+2
source

All Articles