is SIGSEGV delivered to each thread?

2019-01-17 21:50发布

问题:

I have a program in Linux which is multithreaded. There are certain memory areas in which I'm interested to see if they have been written within a certain time period. For that I give only read access to those memory pages and install a signal handler for SIGSEGV. Now my question is, will each thread call the signal handler for itself. Say Thread 1 writes to some forbidden memory area, will it be the one to execute the signal handler?

回答1:

First of all

Signal dispositions are process-wide; all threads in a process share the same disposition for each signal. If one thread uses sigaction() to establish a handler for, say, SIGINT, then that handler may be invoked from any thread to which the SIGINT is delivered.

But read on

A signal may be directed to either the process as a whole or to a specific thread. A signal is thread-directed if

it is generated as the direct result of the execution of a specific hardware instruction within the context of the thread (SIGBUS, SIGFPE, SIGILL, and SIGSEGV)

I am quoting from TLPI.



回答2:

No, per the question title.

To the question body: For the particular signal that you are asking for, yes (otherwise: it depends). The thread causing a segfault will receive the signal.

See signal(7):

A signal may be generated (and thus pending) for a process as a whole (e.g.,
when sent using kill(2)) or for a specific thread (e.g., certain signals, such
as SIGSEGV and SIGFPE, generated as a consequence of executing a specific
machine-language instruction are thread directed [...].