The solution of network program encountering Sigpipe under Linux

Source: Internet
Author: User
Tags signal handler

Http://blog.chinaunix.net/uid-20135786-id-3409085.html

Problem Description:

One of my server programs is working properly under Windows.

However, when there is a non-open exception test on Linux (CentOS 6.3), there is an inexplicable exit. The last trace to a write call results in an exit. Execute the program with GDB and prompt "broken pipe" when exiting.

Problem Analysis:

For a socket that has been closed for two write calls, the second will generate a sigpipe signal that ends the process by default.

The specific analysis can be combined with TCP's "four-time handshake" shutdown. TCP is a full-duplex channel, can be regarded as two single-channel, TCP connection at each end of the two endpoints are responsible for one. When Close is called on the peer, although the intention is to close the entire two channels, but this side just received fin packets. According to the semantics of the TCP protocol, the peer only shuts down the single channel it is responsible for, and continues to receive data. That is, because of the limitations of the TCP protocol, an endpoint cannot be informed that the peer has been completely shut down .

Call the Read method on a socket that has received a FIN packet, and if the receive buffer is empty, return 0, which is often said to indicate that the connection is closed. But when the write method is called for the first time, it returns the correct write (send) if the send buffer is not a problem. But the message sent will cause the RST message to be sent to the end, because the socket on the end has called close, closed completely, neither sent nor received data. Therefore, the second call to the Write method (assuming that the RST is received) generates a sigpipe signal that causes the process to exit.

Workaround:

To avoid a process exit, you can either capture the sigpipe signal or ignore it and set the Sig_ign signal handler function for it:

Signal (Sigpipe, sig_ign);

This way, when the write method is called for the second time, 1 is returned, and errno is set to Sigpipe. The program will know that the peer is closed.

The SIGALRM under the ps:linux appears to be offset 1 milliseconds backwards every 1 seconds, but Windows is tested completely on time, 1 milliseconds.

Methods for ignoring sigpipe signals
struct Sigaction sa;
Sa.sa_handler = sig_ign;//The action to accept the specified signal is ignored
sa.sa_flags = 0;
if (Sigemptyset (&sa.sa_mask) = =-1 | | Initialize signal set is empty
Sigaction (sigpipe, &sa, 0) = =-1) {//Mask sigpipe signal
Perror ("failed to ignore sigpipe; Sigaction ");
Exit (Exit_failure);
}

Pthread line thread how to block sigpipe anomalies
Hi.baidu.com/ailacy/blog/item/a7eb65f8b8b55707d8f9fdd5.html
Http://bbs2.chinaunix.net/viewthread.php?tid=985166&extra=&page=1
In Pthread, you may encounter the problem of program received signal sigpipe, broken pipe, and the workaround is to execute the following code before each thread starts:

#ifndef WIN32
sigset_t Signal_mask;
Sigemptyset (&signal_mask);
Sigaddset (&signal_mask, sigpipe);
int rc = Pthread_sigmask (Sig_block, &signal_mask, NULL);
if (rc! = 0) {
printf ("Block sigpipe error\n");
}
#endif
Of course, this is just one of many ways ~

Based on the experience of Rai, it is possible to block out the sigpipe in the pthread thread as long as the main function is written in the first part of the code above.




[Linux] sigpipe signal and its processing
http://hi.baidu.com/mckeyzhang/blog/item/ D647f26034eee542eaf8f823.html
When writing a socket program under Linux, if you try to send to a disconnected socket, it throws a sigpipe signal to the bottom. The default way to handle this signal is to exit the process, which is not what we expected most of the time. Therefore, we need to overload this signal processing method. You can safely mask Sigpipe by calling the following code:
struct sigaction sa;
Sa.sa_handler = sig_ign;
Sigaction (sigpipe, &sa, 0);
//======================================================================
Sigpipefrom Wikipedia, the free Encyclopediajump to: navigation, search sigpipe Description Write on a pipe with no one to read it Default Action abnormal termination of the process Sa_siginfomacros one

On posix-compliant platforms, Sigpipe are the signal raised when a computer program attempts to write to a pipe WI Thout a process connected to the other end. The symbolic constant for sigpipe are defined in the header file signal.h. Symbolic signal names is used because signal numbers can vary across platforms.

Etymology

SIG is a common prefix for signal names. Pipe refers to the Unix pipe.

Description

Unix supports the principle of piping, which allows processes to send data to other processes without the need for creatin G Temporary files. When a pipe was broken, the process writing to it was sent the sigpipe signal. The default reaction to this signal for a process are to terminate.

A Simple example of piping are the following.

PS L | Head

This command, when run on a unix-like machine (including Linux), returns a list of the processes, limited to ten lines.

    • PS L returns a list of all processes (including those of the other users).
    • Head selects the first ten lines.

When PS had written ten lines, head had received all it needs and exits. PS would receive a sigpipe when it tries to write the remaining lines, causing it to terminate as Well:it are no use writin G data that no one would use. It is also possible, the reading process terminates while reading the data. This would also cause Sigpipe to being sent to the writing process.

One can ignore Sigpipe (using, for example, the signal system call). In this case, all system calls, would cause Sigpipe to be sent would return-1 and set errno to Epipe.

Broken pipe problem under Uinx

www.javaeye.com/topic/456975#

The previous time has encountered "Alarm clock" signal problem when processing the delay function (see my "Unix C delay Function Summary"). Now the test also encountered the "broken pipe" signal problem, the same signal generated by the program is aborted.

The reason my program generates this signal is:
After the client side sends the message through the pipe to the server side, shuts down the client side, then the server side, returns the information to the client side to produce the broken pipe signal.

For generating signals, we can use the method signal (int signum, sighandler_t handler) to set the signal processing before generating the signal. If you do not call this method, the default processing method is called: Abort the program and display the prompt message (which is the problem we often encounter). We can call the processing method of the system, or we can customize the processing method.

Three processing methods are defined inside the system:
1) SIG_DFL/* Default action */
2) sig_ign/* Ignore action */
3) Sig_err/* Error return */

In the project I called Signal (SIGALRM, sig_ign) and signal (Sigpipe, sig_ign) so that when the Sigalam and sigpipe signals are generated, the program is not aborted and the signal is ignored directly.

Custom Processing methods:

    1. void Signal_handle (ing signo)
    2. {
    3. Do something;
    4. }
    5. int main ()
    6. {
    7. Signal (Sigpipe, signal_handle);
    8. ......
    9. }

void Signal_handle (ing signo) {//do something;} int main () {signal (sigpipe, signal_handle); ...}

Linux Network program encounters Sigpipe solution (Turn)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.