Polling timer function in C I've implemented a polling function with a timer in C, that every 10s checks a given condition (I've just replaced it for a log to stdout for testing purposes only) but I would like to know your opinion on this code, namely if there is a simpler way to achieve the same result, what issues may arise concerning performance, thread-safety, memory footprint. I'm interested in writing the most simple, correct and fast code for this. Suggestions are, as always, welcome.

/* includes removed for clarity */

void signalAlarmHandler(int signum) {
  switch(signum) {
  case SIGINT:
    fprintf(stdout, "received interrupt. going to exit.\n");
    exit(0);
    break;
  case SIGALRM:
    fprintf(stdout, "received signal alarm.\n");
    /* checking for condition here */
    break;
  default:
    break;
  }
}

int main(int argc, char* argv[]) {

  if(initializeEnvironment(argc, argv) == -1) {
    return -1;
  }
  else {

    signal(SIGINT, signalAlarmHandler); /* for testing purposes */
    signal(SIGALRM, signalAlarmHandler);

    fprintf(stdout, "starting the signal alarm stuff\n");
    while(1) {
      alarm(10);
      sleep(20);
    }
  }
}
What is a reason for using alarm() with sleep()? Why not just

void sigIntHandler(int signum) {
  fprintf(stdout, "received interrupt. going to exit.\n");
  exit(0);
}

int main(int argc, char* argv[]) {
  if(initializeEnvironment(argc, argv) == -1) {
    return -1;
  }
  signal(SIGINT, signalAlarmHandler); /* for testing purposes */

  while(1) {
    sleep(10);
    /* checking for condition here */
  }
}


Also:


fprintf() is not signal-safe, better not to use it from signal handler
signal() is obsolete and implementation-dependent, use sigaction() for consistent results.