3

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
}
Community
  • 1
  • 1
kuchi
  • 840
  • 11
  • 19

2 Answers2

3

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.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
  • It might also be worth noting that the man page says `The only portable use of signal() is to set a signal's disposition to SIG_DFL or SIG_IGN. The semantics when using signal() to establish a signal handler vary across systems (...); ____do not use it for this purpose____. POSIX.1 solved the portability mess by specifying sigaction(2), which provides explicit control ...` – Brian Vandenberg Sep 18 '13 at 18:47
1

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.

Amine Hajyoussef
  • 4,381
  • 3
  • 22
  • 26