How to handle signal SIGPIPE?

Q. C program on Unix crashed after it attempted to write on a closed socket. How to handle this?

Ans:
In Unix environment, when a process attempts to write on a socket which is shutdown for writing or which is not connected (anymore), OS sends signal SIGPIPE to that process.
Default behavior of the signal SIGPIPE is to terminate the process. To avoid this your process must ignore the signal SIGPIPE. In that case if your process attempts to write on a closed socket, the send() / write() call returns -1 and errno is set to EPIPE. Your process should handle this failure in the write accordingly. This is how you can stop abruptly crashing of your program.

Below C code shows how to ignore signal SIGPIPE.

{
    int ret;
    struct sigaction sa;

    /*
     * There are chances that our application sends 
     * data to a closed socket. This generates SIGPIPE
     * signal, and results into process termination.
     * We must ignore this signal, as our application is 
     * equipped to handle errors happening on socket writes.
     */

    sa.sa_handler = SIG_IGN;
    sa.sa_flags = 0;
    ret = sigaction(SIGPIPE, &sa, NULL);
    assert(-1 != ret);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s