我读/写到由pipe(pipe_fds)
创建的管道。所以基本上使用以下代码,我正在读取该管道:
fp = fdopen(pipe_fds[0], "r");
当我得到某些东西时,我会把它打印出来:
while (fgets(buf, 200, fp)) {
printf("%s", buf);
}
我想要的是,当pipe
到read
上出现一段时间没有任何内容时,我想知道并做到:
printf("dummy");
这可以通过select()实现吗?关于如何做到这一点的任何指示都会很棒。
答案 0 :(得分:11)
假设您想要等待5秒钟然后如果没有写入管道,则打印出“假”。
fd_set set;
struct timeval timeout;
/* Initialize the file descriptor set. */
FD_ZERO(&set);
FD_SET(pipe_fds[0], &set);
/* Initialize the timeout data structure. */
timeout.tv_sec = 5;
timeout.tv_usec = 0;
/* In the interest of brevity, I'm using the constant FD_SETSIZE, but a more
efficient implementation would use the highest fd + 1 instead. In your case
since you only have a single fd, you can replace FD_SETSIZE with
pipe_fds[0] + 1 thereby limiting the number of fds the system has to
iterate over. */
int ret = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
// a return value of 0 means that the time expired
// without any acitivity on the file descriptor
if (ret == 0)
{
printf("dummy");
}
else if (ret < 0)
{
// error occurred
}
else
{
// there was activity on the file descripor
}
答案 1 :(得分:0)
IIRC,select
超时,然后您与FD_ISSET
核对,以确定是否返回了I / O.