Search code examples
cstdoutposix-select

How to use select with stdout?


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?


Solution

  • 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.