Jeremy Friesner
Jeremy Friesner

Reputation: 73071

Why does popen() only work 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 data the first time I call it, and subsequent passes return no 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);
   }
}

Upvotes: 4

Views: 1289

Answers (2)

Matt Joiner
Matt Joiner

Reputation: 118500

Take a look here for an in depth reason as to why fclose and pclose differ and how.

Upvotes: 2

Peter
Peter

Reputation: 132207

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

fclose isn't resetting the pipe state, since it is designed to close files, not pipes. pclose will properly close the pipe, so you can reopen it successfully.

Upvotes: 6

Related Questions