Mat*_*ner 27
设置如下:
FILE *f = popen("./output", "r");
int d = fileno(f);
fcntl(d, F_SETFL, O_NONBLOCK);
Run Code Online (Sandbox Code Playgroud)
现在你可以阅读:
ssize_t r = read(d, buf, count);
if (r == -1 && errno == EAGAIN)
no data yet
else if (r > 0)
received data
else
pipe closed
Run Code Online (Sandbox Code Playgroud)
当你完成后,清理:
pclose(f);
Run Code Online (Sandbox Code Playgroud)
popen()内部调用pipe(),fork(),dup2()(指向子进程的FDS 0/1/2的管道)和execve().您是否考虑过使用这些?在这种情况下,您可以使用将您读取的管道设置为非阻塞fcntl().
更新:这是一个例子,仅用于说明目的:
int read_pipe_for_command(const char **argv)
{
int p[2];
/* Create the pipe. */
if (pipe(p))
{
return -1;
}
/* Set non-blocking on the readable end. */
if (fcntl(p[0], F_SETFL, O_NONBLOCK))
{
close(p[0]);
close(p[1]);
return -1;
}
/* Create child process. */
switch (fork())
{
case -1:
close(p[0]);
close(p[1]);
return -1;
case 0:
/* We're the child process, close read end of pipe */
close(p[0]);
/* Make stdout into writable end */
dup2(p[1], 1);
/* Run program */
execvp(*argv, argv);
/* If we got this far there was an error... */
perror(*argv);
exit(-1);
default:
/* We're the parent process, close write end of pipe */
close(p[1]);
return p[0];
}
}
Run Code Online (Sandbox Code Playgroud)