Versions Compared

Key

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

The signal() function behaves differently in Windows than it does on Linux/BSD systems. When a signal handler is installed with the signal() function in Windows, the default action is restored for that signal after the signal is triggered. Conversely, Linux/BSD systems leave the signal handler defined by the user in place until it is explicitly removed.

Different actions must be taken depending on whether or not you desire signal handlers to be persistent.

Persistent handlers

By default, *nix systems leave the handler in place after a signal is generated.

Non-Compliant Code Example (Windows)

...

Code Block
bgColor#ccccff
void handler(int signum) {
  signal(signum, handler);
  /* rest of handling code */
}

Non-persistent handlers

By default, *nix systems leave the handler in place after a signal is generated.

Non-Compliant Code Example (*nix)

This non-complaint code example fails to reset the signal handler to its default action.

Code Block
bgColor#FFCCCC

#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t e_flag = 0;

void handler(int signum) {
  e_flag = 1;
}

int main(void) {
  signal(SIGINT, handler);
  while(!e_flag) {}
  puts("Escaped from first while()");
  e_flag = 0;
  while(!e_flag) {}
  puts("Escaped from second while()");
  return 0;
}

Compliant Solution (*nix)

The compliant solution explicitly resets the signal handler to its implementation-defined default behavior.

Code Block
bgColor#ccccff

#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t e_flag = 0;

void handler(int signum) {
  signal(signum, SIG_DFL);
  e_flag = 1;
}

int main(void) {
  signal(SIGINT, handler);
  while(!e_flag) {}
  puts("Escaped from first while()");
  e_flag = 0;
  while(!e_flag) {}
  puts("Escaped from second while()");
  return 0;
}

Risk Analysis

Failure to re-establish a persistent signal handler on Windows platforms can lead to unexpected behavior.

...