Making stdin non-blocking

后端 未结 4 1115
情深已故
情深已故 2020-12-18 07:37

I have an exercise where I am required to print a file slowly (1 second intervals) until the file ends, unless the user types a character.

So far, the program output

4条回答
  •  不思量自难忘°
    2020-12-18 08:18

    The terminal is buffering lines. It doesn't send text to the program until you press the Enter key. There might be a way to disable terminal line buffering, but I imagine it is beyond the scope of your assignment.

    It stops when you press Enter. However, it doesn't quit immediately. That's something you'll want to fix. Get rid of that sleep(1).

    Now your program spams text! You gave select a timeout of one second, didn't you?

    // set the time value to 1 second
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    

    The reason the timeout doesn't stick is because select is modifying the timeout value. From the man page:

    On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. (POSIX.1-2001 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing it. Consider timeout to be undefined after select() returns.

    You will need to initialize the timeval before every call to select, not just once at the beginning of the program.

提交回复
热议问题