0

Hi I'm programming a threaded socket program, The program may receive a SIGPIPE signal and will exit, If I catch the signal and ignore it the program will have undefined behavior because I don't know how to handle this as error, How can I catch a signal and notify the current position of the code that it needs to return from a function with error code so the program flow will continue as normal, I want to threat the SIGPIPE as it is error in read/write syscalls, cause i know how to handle read/write errors when I receive them.

{
    signal(SIGPIPE,sig_handler);
}

void sig_handler(int signo)
{
  if (signo == SIGPIPE){
    printf("hi\n");

  }
}
CinCout
  • 9,486
  • 12
  • 49
  • 67
Konk Wory
  • 83
  • 7
  • 4
    Possible duplicate of [How to prevent SIGPIPEs (or handle them properly)](https://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly) – Andrew Henle Jun 05 '17 at 10:15

1 Answers1

2

if you want to ignore the SIGPIPE and handle the error directly in your code. but signal handlers in C have many restrictions . The most easy way is to set the SIGPIPE handler to SIG_IGN. This will prevent any socket write from causing a SIGPIPE signal. To ignore the SIGPIPE signal, use the following code:

signal(SIGPIPE, SIG_IGN);

OR to handle this try this:

#include <signal.h>
/* Catch Signal Handler functio */
void signal_handler(int signum)
{
 printf("Caught signal SIGPIPE %d\n",signum);
}

and In program:

/* Catch Signal Handler SIGPIPE */
signal(SIGPIPE, signal_callback_handler);

Another methode is that set the socket options while creating the socket: change the socket so it never generates SIGPIPE on write().

int num = 1;
setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&num, sizeof(int));
suraj
  • 403
  • 4
  • 15
  • 3
    You should **not** call printf() from within a signal handler. – wildplasser Jun 05 '17 at 11:42
  • we can set a flag in signal handler and can monitor that flag in main programme. for example: declare this flag globly static int alarm = 0; in signal handler : alarm = 1; // set flag and in main programme check this flag – suraj Jun 05 '17 at 12:15