Catch Signals
2003-02-12 01:36:12
Category: c:runtime
Description: Shows how to catch and handle signals. Also shows how to ignore signals.
Author: detour
Viewed: 4482
Rating: (22 votes)


/* signals.c by detour@metalshell.com
 *
 * Shows how to catch and handle signals.  Also shows
 * how to ignore signals.
 *
 * http://www.metalshell.com
 *
 */
 
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
 
void handle_signal(int signum) {
 
  switch(signum) {
    case SIGHUP:
      fprintf(stderr, "Caught signal HUP\n");
      fprintf(stderr, "Now ignoring SIGHUP\n");
      /* SIG_IGN is used to ignore signals.  SIGKILL and SIGSTOP can
         not be ignored. */
      signal(SIGHUP, SIG_IGN);
    case SIGQUIT:
      fprintf(stderr, "Goodbye!\n");
      exit(0);
  }
 
}
 
int main() {
  pid_t pid;
 
  pid = fork();
 
  // Child
  if (pid == 0) {
    // Register the signals
    signal(SIGHUP, handle_signal);
    signal(SIGQUIT, handle_signal);
   
    fprintf(stderr, "\n---------------------\n");
    fprintf(stderr, "Now try 'kill -HUP %d'\n", getpid());
    fprintf(stderr, "Use 'kill -QUIT %d' to end\n", getpid());
 
    // Wait for signal (note: sleep will be interupted by the signal)
    while(1) { 
      if(signal(SIGHUP, handle_signal) == SIG_IGN)
        fprintf(stderr, "Detected SIGHUP as being ignored. Now listening again.\n");
      sleep(5); 
    }
  }
 
  return 0;
}