使用select()与管 [英] using select() with pipe

查看:126
本文介绍了使用select()与管的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的读/写的由创建一个管道管(pipe_fds)。因此,与下面code,基本上,我是从这个管道读取:

I am reading/writing to a pipe created by pipe(pipe_fds). So basically with following code, I am reading from that pipe:

fp = fdopen(pipe_fds[0], "r"); 

和当过我得到的东西,我把它打印出来由:

And when ever I get something, I print it out by:

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

我要的是,当一定时间没有任何的管道出现读取,我想了解它,做的:

What I want is, when for certain amount of time nothing appears on the pipe to read from, I want to know about it and do:

printf("dummy");

这能由选择()?如何做到这一点的任何指针将是巨大的。

Can this be achieved by select() ? Any pointers on how to do that will be great.

推荐答案

比方说,你想等待5秒钟,然后,如果没有写入到管道,你打印出虚拟。

Let's say you wanted to wait 5 seconds and then if nothing was written to the pipe, you print out "dummy."

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
}

这篇关于使用select()与管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆