How to use select with stdout?

拥有回忆 提交于 2019-12-11 02:14:07

问题


I have the following code

    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

I m trying to check the ability to write to the stdout before printf("second printf\n");. but with this code, the select return a value != 1 and then the printf remain unreacheable. it looks like the select return "not possible" to write to the stdout.

Could you explain this behavior?


回答1:


The call to select() is returning -1, and errno is 22 (invalid argument) because you've got junk values in the timeout. Try this:

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

and it should work.



来源:https://stackoverflow.com/questions/14983565/how-to-use-select-with-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!