Search code examples
cprintfstdinfgetsposix-select

Printf before the select call isn't invoked while waiting for Stdin


Here's my code:

int main()
{
    struct timeval tv;
    fd_set fds;
    char cmd[256]={};
    int second = 0, ret;

    printf("Enter Command : ");
    while (1) {
        tv.tv_sec=1;
        tv.tv_usec=0;

        FD_ZERO(&fds);

        FD_SET(STDIN_FILENO, &fds);

        if ((ret = select(STDIN_FILENO+1, &fds, NULL, NULL, &tv)) < 0 ) {
            printf("Select Failed: Exiting\n");
            break;
        }

        if (FD_ISSET(STDIN_FILENO, &fds))
        {
            if (fgets(cmd, 256, stdin) != NULL) {
                printf("Running Command - %s\n", cmd);
                input_invoke_func(cmd);
                printf("Enter Command : ");
            }
        } else {
            second++;
            //print_time(second);
        }
    }
    return 0;
}

I see that the "Enter Command: " string is not printed until I provide any input in STDIN. Please let me know the reason for this behavior !!


Solution

  • Input and output is buffered in the standard library. This means that data which is "printed" or written to a file is not immediately sent to the operating system (and thus to the screen or the file). This is done because actually sending the data has some overhead and it’s more efficient to do this in larger batches. To enforce that data is sent, one can call fflush:

    printf("Enter Command : ");
    fflush(stdout);
    

    Note: flushing happens automatically on newlines when the standard output is connected to a terminal.