[LCP] Is this reentrant?

Paul Gearon gearon at ieee.org
Sat Jan 17 10:46:51 EST 2009


On Wed, Jan 14, 2009 at 11:13 PM, Christopher Howard
<choward at indicium.us> wrote:
> I'm trying to work on making my signal handling safer for my C app. Is
> this considered "reentrant"?:
>
> void signal_handler_function(signal) {
>    global_signal_variable = signal;
> }
>
> "global_signal_variable" is an integer, which is used in the regular
> code to handle the signal according to a switch statement.
>
> If it isn't, what would be considered a safe way to handle the signal in
> the signal handler function, so it can be dealt with in the regular code?

Well, yes and no.

While it's safe for this to happen, it's also a recipe for losing
signals. global_signal_variable can easily be overwritten before you
get to processing it, losing the original signal.

Presuming you have a single threaded program, then assignment by = is
safe to use (it's also usually safe between threads, though there are
exceptions). So you could try something like:

/* global array */
volatile int sigcount[SIGUSR2];
volatile int errors = 0;

void signal_handler_function(signal) {
  if (signal == 0 || signal > SIGUSR2) errors++;
  else sigcount[signal - 1]++;
}

void process_signals() {
  int sig;
  int count;
  for (sig = 0; sig < SIGUSR2; sig++) {
    count = sigcount[sig];
    sigcount[sig] -= count;
    /* do your thing here */
    printf("Got %d of signal #%d\n", count, sig + 1);
  }
  if (errors) {
    count = errors;
    printf("Saw %d unexpected signal numbers\n");
    errors -= count;
  }
}

I don't expect "errors" to ever be incremented, but production code
should never have unexpected behavior for unexpected input, so I
counted any invalid signals (just in case).

Signal processing doesn't pre-empt the -= operation, so it's safe to
use. However, you'll note that I always took a snapshot of the count,
and removed that many, since operations like printf will allow signals
to be processed, thereby possibly incrementing the count.

Paul



More information about the linuxCprogramming mailing list