如何使用select和stdout?

问题描述:

我有以下代码如何使用select和stdout?

fd_set   set; 
    struct   timeval timeout; 
    printf("first printf\n"); // displayed 
    FD_ZERO(&set); 
    timeout.tv_sec = 1; 

    FD_SET(fileno(stdout), &set); 
    if (select(FD_SETSIZE, NULL, &set, NULL, &timeout)!=1) 
    { 
     stdout_closed = true; 
     return; 
    } 
    printf("second printf\n"); // Not displayed 

余米尝试检查printf("second printf\n");之前写入标准输出的能力。但是使用此代码,select会返回值!= 1,然后printf将保持不可刷新状态。它看起来像选择返回“不可能”写入标准输出。

你能解释这种行为吗?

+1

两件事:你不清除'timeout.tv_usec';并且'select'的第一个参数应该是最高描述符加上一个(所以'fileno(stdout)+ 1')。还要记住'select'可以返回错误的'-1',你需要检查它。 – 2013-02-20 15:29:43

对select()的调用返回-1,而errno是22(无效参数),因为您在超时时间内有垃圾值。试试这个:

FD_ZERO(&set); 
timeout.tv_sec = 1; 
timeout.tv_usec = 0; /* ADD THIS LINE to initialize tv_usec to 0 so it's valid */ 

它应该工作。