加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用带管道的select()

发布时间:2020-12-16 03:26:58 所属栏目:百科 来源:网络整理
导读:我正在读/写由pipe(pipe_fds)创建的管道.所以基本上使用以下代码,我正在读取该管道: fp = fdopen(pipe_fds[0],"r"); 当我得到一些东西时,我将它打印出来: while (fgets(buf,200,fp)) { printf("%s",buf);} 我想要的是,当一段时间没有任何东西出现在管道上
我正在读/写由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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读