1

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?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    Two things: You don't clear `timeout.tv_usec`; and the first argument to `select` should be the highest descriptor plus one (so `fileno(stdout) + 1`). Also remember that `select` can return `-1` for errors, you need to check for that. – Some programmer dude Feb 20 '13 at 15:29

1 Answers1

4

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.