Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added alternative CS

...

The sig_atomic_t type is the integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. The type of sig_atomic_t is implementation-defined, although there are constraints. Only assign integer values from 0 through 127 to a variable of type sig_atomic_t to be fully portable.

Another acceptable (although less readable) solution involves specifying the volatile keyword temporarily by using a typecast.

Code Block
bgColor#ccccff

#include <signal.h>

sig_atomic_t i;

void handler(int signum) {
  i = 0;
}

int main(void) {
  i = 1;
  signal(SIGINT, handler);
  while (*(volatile sig_atomic_t *)&i) {
   /* do something */
  }
  return 0;
}

Such a solution may be necessary to prevent the compiler from optimizing away the memory lookup while allowing for caching and optimizations elsewhere in the code.

Risk Assessment

Failing to use the volatile qualifier can result in race conditions in asynchronous portions of the code, causing unexpected values to be stored and leading to possible data integrity violations.

...