[英]Non-blocking pipe using 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()
(將子進程的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];
}
}
從未嘗試過,但我不明白為什么你不能用fileno()獲取文件描述符,使用fcntl()設置為非阻塞,並使用read()/ write()。 值得一試。
你看過popen()手冊頁的“see also”部分嗎?
快速谷歌搜索顯示此頁面: http : //beej.us/guide/bgnet/output/html/singlepage/bgnet.html#blocking談論阻止和非阻止訪問文件描述符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.