当我在Mac上运行下面的程序(OS/X 10.6.4)时,我得到以下输出:
$ ./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
Run Code Online (Sandbox Code Playgroud)
为什么popen()只在我第一次调用它时读取数据,后续传递没有返回输出?
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
你应该使用pclose而不是fclose.(经过测试和验证.)
fclose没有重置管道状态,因为它被设计为关闭文件而不是管道.pclose将正确关闭管道,以便您可以成功重新打开它.