tags:

views:

93

answers:

3

I'm witting an application based on a server and various client but I'm having a problem with the send command. Whenever I do ctrl+c on the client side the send operation kills the thread which is in and the process running (in order to have multiple clients I set a thread to which one).

If the client ends (doing the close socket) properly the server doesn't die, but when I use the ctrl+c combination on the client both exit.

What can I do to prevent send commando to have this behavior?

Thx in advance

+1  A: 

Check out beej's guide to signals. You need to catch and handle the signal for CTRL-C, which is SIGINT (Terminal interrupt signal).

pyrony
Done thx alot for the recommendation
out_sider
+1  A: 

In order to close the socket connection and properly terminate your client program on ctrl-c, you may need to provide an appropriate signal handler for SIGINT. This is accomplished using the signal() or preferably, sigaction() functions.

This question and its answers may be of interest: How should I close a socket in a signal handler?

On your server program, you should be checking for errors on every function involving the socket such as accept() or recv()/read() by checking the function's return value. If the return value from the function indicates an error (usually -1), look at errno. The value of errno should provide some indication as to the nature of the error and allow the error case to be handled appropriately. This should help you to better handle the condition where the connection is lost when the client application terminates unexpectedly.

jschmier
A: 

Let me summarize what I believe your problem is: Whenever you are hitting ctrl-c to close the client, the server exits. And you want this behavior to be handled, in a way that the server does not crash as above. If this is true, kindly read on, I think I may be able to shed some light on the actual issue, it does not really have much to do with using (or not using) a proper signal handle.

When you are closing the client using ctrl-c, OS will stop the client process and close all the sockets opened by it. As part of that, a FIN will be sent to the server.

Please review your code. I believe you would have written the code in a way that it is blocked in a read() call from the socket with the client concerned. Now, when the FIN sent above reaches the server side socket, this read will return with a value of 0.

If your code does not check for this condition and tries to write something back to the client, ultimately (I skip few steps that happen intermediately) it will receive a SIGPIPE. This will cause your server to crash.

If the above scenario is true, you have 2 way outs: 1. check for read() returning 0 and gracefully continue. 2. install a signal handler for SIGPIPE.

I prefer the 1st method, btw.

iShaan84