Sockets: clients exit without any return when server shuts down
I'm making a simple client/server TCP communication stream and my problem is that when I kill the server app, the client app just exits gracefully. There's no output to STDERR, and 开发者_如何学Pythonrecv() doesn't return 0 or -1, the client app just stops.
On the other hand, if I kill the client app, the server app gets return values of 0 from send(), which is expected.
Any help in this issue is greatly appreciated!
This is probably due to SIGPIPE
being raised, which will happen on an attempt to write to a connection that has been closed by the other end. By default, SIGPIPE
will summarily terminate the process, to prevent a bunch of system resources being wasted generating output that will go nowhere. To prevent this, you can ignore the signal:
signal(SIGPIPE, SIG_IGN);
If you do this, the send
call should operate as expected.
When you kill your client application, the operating system closes all its open IO handles. When a TCP connection is closed this way, it sends a FIN to its peer. In this regard, having your client killed is indistinguishable from having it exit gracefully.
Once a TCP connection is established, there is no notion of "client" and "server"; it's a simple, bi-directional communication channel. The result, from a network/sockets point of view, is the same regardless of which side gets aborted.
If you're seeing differences in behavior, then it's in the programming of the two applications. A blocking recv()
call should return with the number of bytes that were available when the connection closed, or possibly -1 for an error.
I suggest using strace <client program and args>
on your process to see exactly what's occurring with that system call.
精彩评论