我想使用
popen()
打开一个管道,并以非阻塞的方式访问它的'读'端口。如何实现?(我找到的例子都是阻塞/同步的)设置如下:
FILE *f = popen("./output", "r");
int d = fileno(f);
fcntl(d, F_SETFL, O_NONBLOCK);
现在您可以阅读:
ssize_t r = read(d, buf, count);
if (r == -1 && errno == EAGAIN)
no data yet
else if (r > 0)
received data
else
pipe closed
完成后,进行清理:
pclose(f);
popen()
内部调用了 pipe()
、fork()
、dup2()
(将子进程的文件描述符 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];
}
}
我从未尝试过,但我不认为你不能使用fileno()获取文件描述符,使用fcntl()设置为非阻塞,并使用read()/write()。值得一试。