How can I cancel a blocking call such as select()

2019-07-18 12:34发布

问题:

As the title says, how can I cancel a blocking call such as select() or (in the case of serial comm and similar) read() from another thread? What is the traditional way of solving things like this? I suppose one could use a small timeout and that would probably work fine but that seems like a bit of a hack to me.

回答1:

The traditional way of interrupting select(2) is the self-pipe trick. The input/output calls are better served by having the descriptors non-blocking and handling EAGAIN.



回答2:

In these situations you should probably use a small or immediate timeout and have additional logic that handles when/how/why the next select/read attempt is made.