【发布时间】:2019-06-08 03:46:50
【问题描述】:
The manpage for popen 表示“从“弹出”流中读取命令的标准输出。
但是,我似乎无法在下面的简单程序中获得子进程输出。 “reader”父进程在读取时阻塞(无论是使用fgets还是fread)
我错过了什么?
使用 gdb 附加到 pinger 程序表明它正在循环并调用 printf 以输出文本。 fgets 在父母一方没有检测到任何东西......
PINGER.C
#include <string.h>
#include <stdio.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
int i = 0;
while (1)
{
printf("stdout %d\n", i++);
sleep(1);
}
}
POPENTEST.C
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
char *cmd = "./pinger";
printf("Running '%s'\n", cmd);
FILE *fp = popen(cmd, "r");
if (!fp)
{
perror("popen failed:");
exit(1);
}
printf("fp open\n");
char inLine[1024];
while (fgets(inLine, sizeof(inLine), fp) != NULL)
{
printf("Received: '%s'\n", inLine);
}
printf("feof=%d ferror=%d: %s\n", feof(fp), ferror(fp), strerror(errno));
pclose(fp);
}
输出
$ ./popenTest
fp open
【问题讨论】: