using fgets as non-blocking function c++

前端 未结 5 626
情书的邮戳
情书的邮戳 2020-12-12 01:23

I\'m writing a program that reads in a loop from the stdin, using the function fgets, as follows:

while(fgets(buffer2, BUFFERSIZE , stdin) != NULL){
  //So         


        
5条回答
  •  [愿得一人]
    2020-12-12 02:00

    If you have a proper POSIX environment, you can use select() or poll() to check for input on stdin's descriptor before calling fgets()... read().

    Jan's comment below (thanks!) explains why you can't use fgets() with this approach... summarily, there's an extra layer of buffering in the FILE object, and data can already be waiting in though the select() finds nothing more on the file descriptor... preventing your program from responding in a timely way, and potentially hanging if some other system is waiting for a response to already sent data before sending more on stdin.

提交回复
热议问题