PoiNtEr->: Linux Signals – Example C Program to Catch Signal (SIGINT)

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Friday, March 9, 2012

Linux Signals – Example C Program to Catch Signal (SIGINT)



What is a signal? Signals are software interrupts.
A robust program need to handle signals. This is because signals are a way to deliver asynchronous events to the application.A user hitting ctrl+c, a process sending a signal to kill another process etc are all such cases where a process needs to do signal handling.
Linux Signals
In Linux, every signal has a name that begins with characters SIG. For example 
 * +--------------------+------------------+
 * |  POSIX signal      |  default action  |
 * +--------------------+------------------+
 * |  SIGHUP               |  terminate |
 * |  SIGINT                  | terminate |
 * |  SIGQUIT                | coredump |
 * |  SIGILL                     | coredump |
 * |  SIGTRAP                | coredump |
 * |  SIGABRT/SIGIOT    | coredump |
 * |  SIGBUS            | coredump |
 * |  SIGFPE            | coredump |
 * |  SIGKILL           | terminate(+) |
 * |  SIGUSR1           | terminate |
 * |  SIGSEGV           | coredump |
 * |  SIGUSR2           | terminate |
 * |  SIGPIPE           | terminate |
 * |  SIGALRM           | terminate |
 * |  SIGTERM           | terminate |
 * |  SIGCHLD           | ignore   |
 * |  SIGCONT           | ignore(*) |
 * |  SIGSTOP           | stop(*)(+)   |
 * |  SIGTSTP           | stop(*)   |
 * |  SIGTTIN           | stop(*)   |
 * |  SIGTTOU           | stop(*)   |
 * |  SIGURG            | ignore   |
 * |  SIGXCPU           | coredump |
 * |  SIGXFSZ           | coredump |
 * |  SIGVTALRM         | terminate |
 * |  SIGPROF           | terminate |
 * |  SIGPOLL/SIGIO     | terminate |
 * |  SIGSYS/SIGUNUSED  | coredump |
 * |  SIGSTKFLT         | terminate |
 * |  SIGWINCH          | ignore   |
 * |  SIGPWR            | terminate |
 * |  SIGRTMIN-SIGRTMAX | terminate       |
 * +--------------------+------------------+
 * |  non-POSIX signal  |  default action  |
 * +--------------------+------------------+
 * |  SIGEMT            |  coredump |
 * +--------------------+------------------+

Example C Program to Catch Signal "SIGINT"
//sigint.c
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
}
int main(void)
{
  if (signal(SIGINT, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGINT\n");
  // A long long wait so that we can easily issue a signal to this process
  while(1) 
    sleep(1);
  return 0;
}


gcc -o sigint sigint.c
Output:



No comments:

Post a Comment