Making stdin non-blocking

后端 未结 4 1118
情深已故
情深已故 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:20

    Part of your problem is that you are using sleep(1) which will cause that line to take a full second to execute. If the user types a character, they will have to wait up to a full second before your program responds. So even once you get the non-blocking portion working you will still have issues.

    The solution is to use nanosleep or usleep to pause the program for less than 1 second. My recommendation would be to sleep for 1/100 of a second *using one of those functions) and check for user key presses every time. On the 100th time, output the next portion of the file. That way the file still goes the right speed, but the user can stop it whenever they want and the program will respond to their command very quickly.

提交回复
热议问题