what is the use of SA_ONSTACK in sigaction?
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?
Solution 1:
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.
Solution 2:
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