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>
#include <unistd.h>

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

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

void handler(int signum) {
  sleep(1);
  log_message();
  free( info);
}

int main(void) {
  signal(SIGINT, handler);
  info = (char*) malloc(MAXLINE);

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

    log_message();

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

This program has four potential problems. The first is that the log_message() function calls fprintf(), which is an unsafe function to call from within a signal handler..., because the handler might have been called when global data (such as stderr) was in an inconsistent state. In general standard I/O is never safe to invoke within a signal handler.

...