About detecting TCP connection disconnection

    Because of the project requirements, C programming under linux needs to be used for development, which was previously carried out under STM. So I am not particularly familiar with some APIs and development skills of linux. Because the network communication of the project is used on the TCP protocol. If the server is disconnected during the connection, the client will also be disconnected accordingly, but if the server continues to connect, the client should reconnect at this time, so there must be a mechanism to detect, previously used the return value of recv if it is -1 is for reconnection, because the socket number must be closed before reconnection, and you will find that it is easy to connect repeatedly. Unreasonable, so refer to http://blog.sina.com.cn/s/blog_6b633e8f0100kt39.html this blog has been modified.

When the server closes a connection, if the client continues to send data. According to the provisions of the TCP protocol, an RST response will be received. When the client sends data to the server, the system will send a SIGPIPE signal to the process, telling the process that the connection has been disconnected and do not write any more.
According to the default processing rules of the signal, the default execution action of the SIGPIPE signal is terminate (terminate, exit), so the client will exit. If you don't want the client to exit, you can set SIGPIPE to SIG_IGN

Such as: signal(SIGPIPE, SIG_IGN);
At this time, SIGPIPE is handed over to the system for processing.

If the server uses fork, it needs to collect garbage processes to prevent the generation of zombie processes. It can be handled like this:
signal(SIGCHLD, SIG_IGN);
hand it over to the system init for recycling.
Here, the child process will not generate zombie processes.


When writing a socket program under linux, if you try to send to a disconnected socket, the bottom layer will throw a SIGPIPE signal.
The default handling of this signal is to exit the process, which is not what we expect most of the time. So we need to overload the handler for this signal. SIGPIPE can be safely blocked by calling the following code:
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigaction( SIGPIPE, &sa, 0 );

The signal handle set by signal can only function once. After the signal is captured once, the signal handle will be restored to the default value.
The signal handle set by sigaction can be valid until you change its setting again.

struct sigaction action;
action.sa_handler = handle_pipe;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGPIPE, &action, NULL);
void handle_pipe(int sig)
{

        //Close the previous socket number before reconnecting
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325598483&siteId=291194637