Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Only call asynchronous-safe functions within signal handlers. Violating this could result in several issues, including heap damage and semantic vulnerabilities.

According to the "Signals and Interrupts" section of the C99 Rationale:

...

Code Block
bgColor#FFcccc
#include <signal.h>

char *foo;

void int_handler() {
  free(foo);
  _Exit(0);
}

int main(void) {
  foo = malloc(15);
  if(foo == NULL) {
    /* handle error condition */
  }

  signal(SIGINT, int_handler);
  strcpy(foo, "Hello World.");
  puts(foo);
  free(foo);
  return 0;
}

Note:

...

The

...

_Exit()

...

function

...

causes

...

immediate

...

program

...

termination,

...

and

...

is

...

async-safe,

...

whereas

...

exit()

...

calls

...

cleanup

...

routines

...

first,

...

and

...

is

...

not

...

async-safe.

...

Compliant Solution

Signal handlers should be as minimal as possible, only unconditionally setting a flag where appropriate, and returning. You They may also call the _Exit() function to immediately terminate program execution..

Code Block
bgColor#ccccff
#include <signal.h>

char *foo;

void int_handler() {
  _Exit(0);
}

int main(void) {
  foo = malloc(15);
  if(foo == NULL) {
    /* handle error condition */
    return 0;
  }
  signal(SIGINT, int_handler);
  strcpy(foo, "Hello World.");
  puts(foo);
  free(foo);
  return 0;
}

...