How to exit a blocking recv() call? [duplicate]

2019-01-08 01:15发布

问题:

This question already has an answer here:

  • [c++winsock2.0]How to abort winsock blocking call ? 3 answers

Based on this question, when you call closesocket() on a socket that recv() is already using, then an RST packet will be sent to the other side instead of performing a graceful disconnection (4-way handshake).

But I wish to perform a graceful disconnection, so I need to exit recv() before calling closesocket().

Is there a way to do that?

回答1:

You can shutdown() the socket for input. The recv() will unblock and return zero and everybody will be happy.



回答2:

The real issue here is that a sure kill, terminatethread(), has all kinds of warnings on it about bad effects of its use. I have been using this method to exit an recv(). The windows docs says "you must know what the thread is doing before applying terminatethread", well, we know what it is doing, its in recv(). The question is not what the THREAD is doing, its what windows kernel is doing.

In the embedded system RTOSes I have done killthread() is doable. Its not EASY, you have to find every single lock and resource owned by the thread and back it out. Only the OS has that kind of information (and power).