【问题标题】:Pipe and select : sample code not working管道和选择:示例代码不起作用
【发布时间】:2011-03-03 19:57:33
【问题描述】:

我错过了什么吗?

我想通过在另一个线程中调用 write 来退出选择...它永远不会退出选择。

代码在 OSX snow 上测试。

fd_set rio, wio;

int pfd[2];

无效测试(int sleep_time)
{
睡眠(睡眠时间);

char buf[] = "1";

write(pfd[1], buf, 1);

}

int main(int argc, char* argv[])

{

char buff[80];
int ended = 0;

pipe(pfd);

FD_ZERO(&rio);
FD_ZERO(&wio);

FD_SET(pfd[1], &wio);   
FD_SET(pfd[0], &rio);

pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of thread attributes */
pthread_attr_init(&attr);

pthread_create(tid, NULL, test, 3);

while (!ended)
{
// Check my numbers ... they do not go over 1 ... so 2
if (select(2, &rio, &wio, NULL, 0) < 0)
    perror("select");
else
{
    if (FD_ISSET(pfd[1], &wio))
    {
        if ((read(pfd[0], &buff, 80))<0) 
               perror("read");
         ended = 1;
    }
 }

}

【问题讨论】:

    标签: macos select pipe


    【解决方案1】:

    我相信你有 2 个错误:

    1 - 您的 select 调用将检查限制为 fd 2 的最大值,因为 0、1 和 2 已经为 stdin、stdout、stderr 打开了管道,因此管道可能会有更大的 FD。管道 FD 可能具有 fd 3 和 4,因此您实际上需要确定 2 个管道 FD 中较大的一个,并将其用于选择中的限制而不是 2。

    int maxfd = pfd[1];
    if( pfd[0] > maxfd ) {
        maxfd = pfd[0];
    }
    ...
    

    2 - 选择返回后,您正在查看 wio 和管道写入 FD,而您需要查看是否有任何可用的 READ:

            if (FD_ISSET(pfd[0], &rio)) {
    

    【讨论】:

      猜你喜欢
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多