为什么 popen() 只工作一次?
当我在 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
为什么 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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
pclose
而不是fclose
。 (经过测试和验证。)fclose
不会重置管道状态,因为它旨在关闭文件,而不是管道。pclose
将正确关闭管道,因此您可以成功重新打开它。You should use
pclose
instead offclose
. (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.请查看此处深入了解解释为什么
fclose
和pclose
不同以及如何不同。Take a look here for an in depth reason as to why
fclose
andpclose
differ and how.