How can I prevent scanf() to wait forever for an input character?

前端 未结 5 2144
悲哀的现实
悲哀的现实 2020-12-01 16:56

I want to fulfill the following things in a console application:

  1. If user inputs a character, the application will do the corresponding task. For example, if us
5条回答
  •  孤城傲影
    2020-12-01 17:14

    Here is a working example of how to do this with poll (probably the most 'correct' way on Linux):

    #include 
    #include 
    #include 
    
    int main()
    {
        struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };
        char string[10];
    
        if( poll(&mypoll, 1, 2000) )
        {
            scanf("%9s", string);
            printf("Read string - %s\n", string);
        }
        else
        {
            puts("Read nothing");
        }
    
        return 0;
    }
    

    The timeout is the third argument to poll and is in milliseconds - this example will wait for 2 seconds for input on stdin. Windows has WSAPoll, which should work similarly.

提交回复
热议问题