I have this assignment to do:
Write a function void myfunct(void(*f)(int sig))
which sets f
as handler to all the possible signals.
I have two problems:
f
as handler given that it takes a parameter? Shouldn't it not have any parameters?Thank you.
- How can a get all the possible signals? Is there a function for this? Can I iterate through them in some way?
Most implementation provide a constant such as NSIG
(Glibc provides NSIG
) or _NSIG
(Linux provides _NSIG). So, you can loop through that constant and set the same signal handling function for all of them.
There's no POSIX defined value for "highest signal number". There's been a proposal in POSIX to add a macro NSIG_MAX
.
{NSIG_MAX}
Maximum possible return value of sysconf(_SC_NSIG). See [cross-ref to XSH sysconf()]. The value of {NSIG_MAX} shall be no greater than the number of signals that the sigset_t type (see [cross-ref to ]) is capable of representing, ignoring any restrictions imposed by sigfillset() or sigaddset().
But it hasn't made it to POSIX yet (most probably it'll a part of the POSIX version - issue 8).
- Will it really work to set the function f as handler given that it takes a parameter? Shouldn't it not have any parameters?
The parameter that the signal handling function takes doesn't matter when you are setting a signal disposition. It takes the signal number but that doesn't prevent you from using it as a handler for multiple signals.
But there are special cases you need to handle. Certain signals that can't caught or ignored (SIGKILL
and SIGSTOP
). There are other signals (SIGFPE
, SIGILL
and SIGSEGV
) for which, while allowed to caught, the signal handler can't return to its caller (i.e. you need exit from the signal handler).