使用带管道的select()

我正在读/写由pipe(pipe_fds)创建的管道.所以基本上使用以下代码,我正在读取该管道:
fp = fdopen(pipe_fds[0],"r");

当我得到一些东西时,我将它打印出来:

while (fgets(buf,200,fp)) {
    printf("%s",buf);
}

我想要的是,当一段时间没有任何东西出现在管道上阅读时,我想了解它并做:

printf("dummy");

这可以通过select()实现吗?关于如何做到这一点的任何指针都会很棒.

解决方法

假设您想要等待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,&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
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...