The correct way to use a signal handler

The correct way to use a signal handler … here is a solution to the problem.

The correct way to use a signal handler

What is the correct way to use a signal handler?

I saw the following code from this question and wondered why you still need to put signal(SIGSEGV,sig_func); Put in sig_func? When a process receives a SIGSEGV signal, doesn’t this create an endless loop?

void sig_func(int sig)
{
  write(1, "Caught signal 11\n", 17);
  signal(SIGSEGV,sig_func);
}

int main()
{

signal(SIGSEGV,sig_func); Install the signal handler

Do work here
}

Solution

signal manual says:

Finally, if the handler is set to a function sighandler then first either the handler is reset to SIG_DFL or an implementation-dependent blocking of the signal is performed and next sighandler is called with argument signum.

Repeated calls to signal are used to reinstall the custom handler after it is (possibly) reset to SIG_DFL.

Related Problems and Solutions