Versions Compared

Key

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

...

In this noncompliant code example, the signal handler handler() is bound to signum.

Code Block
bgColor#ffcccc
langc
void handler(int signum) {
  if (signal(signum, handler) == SIG_ERR) {
    /* Handle error */
  }
  /* Handle signal */
}
/* ... */
if (signal(SIGUSR1, handler) == SIG_ERR) {
  /* Handle error */
}

...

For persistent platforms, calling the signal() function from within the signal handler is unnecessary.

Code Block
bgColor#ccccff
langc
void handler(int signum) {
  /* Handle signal */
}
/* ... */
if (signal(SIGUSR1, handler) == SIG_ERR) {
  /* Handle error */
}

...

POSIX defines the sigaction() function, which assigns handlers to signals like signal() but also allows the caller to explicitly set persistence. Consequently, the sigaction() function can be used to eliminate the race window on nonpersistent operating systems.

Code Block
bgColor#ccccff
langc
void handler(int signum) {
  /* Handle signal */
}

/* ... */

struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0;
if (sigemptyset( &act.sa_mask) != 0) {
  /* Handle error */
}
if (sigaction(SIGUSR1, &act, NULL) != 0) {
  /* Handle error */
}

...

The following code example resets a signal handler to the system's default behavior.

Code Block
bgColor#ccccff
langc
void handler(int signum) {
#ifndef WINDOWS
  if (signal(signum, SIG_DFL) == SIG_ERR) {
    /* Handle error */
  }
#endif
  /* Handle signal */
}
/* ... */
if (signal(SIGUSR1, handler) == SIG_ERR) {
  /* Handle error */
}

...