Correct way to use signal handlers

1.4k views Asked by At

What is the correct way to use signal handlers?

I saw the codes below from this question and was wondering why do you still need to put signal(SIGSEGV,sig_func); inside the sig_func? Wouldn't that create an unending loop when the process receives a SIGSEGV signal?

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
}
2

There are 2 answers

1
Linus Kleen On BEST ANSWER

The 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.

The repeat call to signal is used to reinstall the custom handler after it (might) have been reset to SIG_DFL.

0
Amine Hajyoussef On

in the example you provided, calling signal in sig_funct is useless because you have already set the signal handler in main and did not change it inside your handler.

considering your second question,no,it will not create an unending loop because signal() sets the disposition of the signal SIGSEGV to handler but do not execute it.