Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of SA_ONSTACK in sigaction?

Tags:

c

linux

signals

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?

like image 911
Whoami Avatar asked Mar 03 '12 16:03

Whoami


People also ask

What does sigaction function do?

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.

Should I use signal or sigaction?

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.

What is the difference between signal and sigaction?

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.

How do you get PID from sigaction?

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.


2 Answers

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.

like image 190
Mat Avatar answered Sep 25 '22 21:09

Mat


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

like image 22
WGH Avatar answered Sep 23 '22 21:09

WGH