I’ve got a small program that does a large amount of processing. The progress of which you can get a print of by hitting the enter key.
The way I’ve implemented this is by having the processing done in the main thread whilst I have a pthread constantly looping on getchar() to wait for the enter key.
The problem is when I have finished with the processing. When this happens the main thread finishes, but still waits for enter to be pressed because getchar() is blocking.
How do I “cancel” getchar()?
The most portable solution I can think of is:
pipe()to construct two FDs, one a reader and the other a writer. Give the reader to yourread()loop; give the writer to whoever needs to terminate the reader.select()from the read thread to wait for readability of both stdin and the reader pipe.Now, all you should have to do is close the other end of the pipe and this will wake up the reader thread out of its
select()and it should then terminate.The traditional approach involves using signals, however this pipe-based solution allows you to check for input on stdin as well as check if you should terminate using the same polling mechanism.
Note that mixing
getchar()andselect()will not work, sincegetchar()will effectively usefread()under the hood, and the buffering performed byfread()can causeselect()to block even though there is data available. Useread()instead. Here is an example program I used to test this approach.Example run: