Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper usage of volatile sig_atomic_t

According to this site, one can use variables of type volatile sig_atomic_t inside a signal handler. Now my question is, would for example something like the following code still be atomic and thus introduce no race conditions?

Assume that we are using a multicore processor (EDIT: running a multithreaded program). Does volatile sig_atomic_t even work for multicore systems in the first place or should we use the atomic<unsigned int> of C++11 for signal handlers on a multicore system (EDIT: running a multithreaded program)?

volatile sig_atomic_t a;

static void signal_handler(int sig, siginfo_t *si, void *unused)
{
  int b;
  ................
  b = ...;
  a = a | b;
  ................
}
like image 821
MetallicPriest Avatar asked Dec 13 '11 11:12

MetallicPriest


People also ask

What is volatile Sig_atomic_t?

The definition of sig_atomic_t is: "The type defined is sig_atomic_t which is the (possibly volatile-qualified) integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts." The standard clearly states " sig_atomic_t ... is ... an object that can be accessed as an ...

What is a volatile object?

Objects that are declared as volatile are not used in certain optimizations because their values can change at any time. The system always reads the current value of a volatile object when it is requested, even if a previous instruction asked for a value from the same object.

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.


1 Answers

Unless your program is multithreaded, signal handlers never run concurrently with other code in your program, and they certainly never run concurrently with the code they've interrupted. Your code is fine as long as the signal sig is masked for the duration of the signal handler.

like image 180
R.. GitHub STOP HELPING ICE Avatar answered Oct 01 '22 18:10

R.. GitHub STOP HELPING ICE