All about programming in GNU/LINUX

Catching SIGINT(ctrl+c) signal in GNU/LINUX

/*SIGINT
 *RUN the code and press ctrl+c ,This signal is sent to all processes in the foreground process group when the user
 *enters the interrupt character (usually Ctrl-C). The default behavior is to
 *terminate; however, processes can elect to catch and handle this signal, and
 *generally do so to clean up before terminating.*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
/* handler for SIGINT */
static void sigint_handler (int signo)
{

  printf (“Caught SIGINT!\n”);
  exit (EXIT_SUCCESS);
}
int main (void)
{
/*
* Register sigint_handler as our signal handler
* for SIGINT.
*/
if (signal (SIGINT, sigint_handler) == SIG_ERR) {
 fprintf (stderr, “Cannot handle SIGINT!\n”);
exit (EXIT_FAILURE);
}

pause (); //pause waits till a signal is generated
return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s