Versions Compared

Key

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

...

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

enum { MAXLINE = 1024 };
char *info = NULL;

void log_message(void) {
  fprintf(stderr, info);
}

void handler(int signum) {
  log_message();
  free(info);
  info = NULL;
}

int main(void) {
  if (signal(SIGINT, handler) == SIG_ERR) {
    /* Handle error */
  }
  info = (char*)malloc(MAXLINE);
  if (info == NULL) {
    /* Handle Error */
  }

  while (1) {
    /* Main loop program code */

    log_message();

    /* More program code */
  }
  return 0;
}

This program has four potential problems. The first is that it is unsafe to call the fprintf() function from within a signal handler because the handler may be called when global data (such as stderr) is in an inconsistent state. In general, it is not safe to invoke I/O functions within a signal handler.

...

Wiki Markup
The following table from the the Open Group Base Specifications \[[Open Group 04|AA. C References#Open Group 04]\], defines a set of functions that are asynchronous&mdash;signal-safe. Applications may invoke these functions, without restriction, from signal-catching functionshandler.

Asynchronous—signal-safe functions

...

All functions not in this table are considered to be unsafe with respect to signals. In the presence of signals, all functions defined by IEEE standard 1003.1-2001 behave as defined when called from or interrupted by a signal -catching functionhandler, with a single exception: when a signal interrupts an unsafe function and the signal -catching function handler calls an unsafe function, the behavior is undefined.

...

The OpenBSD signal() man page list lists a few additional functions that are asynchronous-safe in OpenBSD but "probably not on other systems" including: snprintf(), vsnprintf(), and syslog_r() (but only when the syslog_data struct is initialized as a local variable).

...