使用带管道的select()

前端之家收集整理的这篇文章主要介绍了使用带管道的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
}
原文链接:https://www.f2er.com/c/111377.html

猜你在找的C&C++相关文章