Search code examples
csocketsioprintfposix-select

select() function don't allow printf() without "\n" in the end


I have a problem using select(): it acts strange in my program and I can't understand why.

#include <stdio.h>
#include <netdb.h>

int main()
{
char msg[1024];

fd_set readfds;
int stdi=fileno(stdin);

FD_SET(stdi, &readfds);

for (;;) {
    printf("Input: ");
    select(stdi+1, &readfds, NULL, NULL, NULL);

    if (FD_ISSET(stdi, &readfds))
        {
        scanf("%s",msg);
        printf("OK\n");
        }
    }
}

What program behavior do you expect? Probably same as me (123 is a string I enter):

Input: 123
OK

But the real program behavior looks like this:

123
Input: OK

Let's change arguement in call printf("Input: ") to "Input: \n". What we'll get is

Input: 
123
OK

So select() function is freezing output untill next printf() ending with "\n".

What can I do to get the behavior I expected?


Solution

  • By default, stdout is line-buffered, meaning output is not written until a '\n' is encountered. So, you need to use fflush after the printf to force the buffered data to be written to the screen.

    Also, instead of doing fileno(stdin), you can just use the constant STDIN_FILENO (which is always 0).