When the signal is delivered, the signal handler is executed on the stack of the process.
If SA_ONSTACK is used in sigaction()
, then a different stack is used.
What is the use of using different stack? Any use case example?
The sigaction() function examines, changes, or both examines and changes the action associated with a specific signal. The sig argument must be one of the macros defined in the <signal. h> header file. If sigaction() fails, the action for the signal sig is not changed.
Therefore, if you use signal to save and later reestablish an action, it may not be able to reestablish properly a handler that was established with sigaction . To avoid having problems as a result, always use sigaction to save and restore a handler if your program uses sigaction at all.
The signal() function does not (necessarily) block other signals from arriving while the current handler is executing; sigaction() can block other signals until the current handler returns. The signal() function (usually) resets the signal action back to SIG_DFL (default) for almost all signals.
1. options are described in man sigaction. A good choice is options=SA_RESTART . To know the PID of the process which sent a signal, set options=SA_SIGINFO , and use a sa_sigaction callback instead of sa_handler ; it will receive a siginfo_t struct, having a si_pid field.
One use of an alternate stack is to try and handle SIGSEGV
properly.
If your process just received a SIGSEGV
because it exceeded its stack limit, you can't run the signal handler on the process's stack - it's full already. Having an alternate stack allows you to (carefully) run some more or less graceful shutdown in that case.
Another interesting example is when you link "normal" code, like C, with some other language runtime that uses small stacks and/or split stacks, like Go language.
In Go, goroutines (lightweight threads) have rather small stack that's expanded as needed. Basically, every function's prologue checks that the stack has enough space left, and grows the stack if it doesn't.
When Go calls C code through cgo, it automatically expands the stack to meet C expectations.
However, if C code installs signal handlers, they might be called at any time, including when there's no enough stack space left.
So any C code that links with Go code must use SA_ONSTACK
in order to not crash.
https://golang.org/pkg/os/signal/#hdr-Go_programs_that_use_cgo_or_SWIG
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With