微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用带管道的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.jb51.cc/c/111377.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐