Unless you use the raise()
from Standard C or kill()
with the value from getpid()
as the PID argument, signal events are asynchronous.
In single-threaded code on a multi-core machine, it means that you cannot tell what is happening in the 'do something to variable i
' code. For example, that code might have just fetched the value from i
and have incremented it, but not yet saved the incremented value. If the signal handler function f()
reads i
, modifies it in a different way, saves the result and returns, the original code may now write the incremented value of i
instead of using the value modified by f()
.
This is what leads to the many constraints on what you can do in a signal handler. For example, it is not safe to call printf()
in a signal handler because it might need to do memory allocation (malloc()
) and yet the signal might have arrived while malloc()
was modifying its linked lists of available memory. The second call to malloc()
might get thoroughly confused.
So, even in a single-threaded program, you have to be aware and very careful about how you modify global variables.
However, in a single-threaded program, there will be no activity from the main loop while the signal is being handled. Indeed, even in a multi-threaded program, the thread that receives (handles) the signal is suspended while the signal handler is running, but other threads are not suspeded so there could be concurrent activity from other threads. If it matters, make sure the access to the variables is properly serialized.
See also: