During the developing phase of programs for my customers, I have to think that they can use the CTRL-C combo to interrupt the execution of my code. 

In some cases, for example in a program that makes only some computations, I can avoid catching this event.

In some other cases, for example when my program has activated a hardware watchdog timer which will reset the system, I must handle this event to deactivate the hardware timer.

To handle this event I use the signal() function from the signal.h library.



#include <signal.h>

void (*signal(int sig, void (*func)(int)))(int);

or in the equivalent but easier to read typedef'd version:


typedef void (*sig_t) (int);

sig_t signal(int sig, sig_t func);

This signal() facility is a simplified interface to the more general sigaction(2) facility.

Signals allow the manipulation of a process from outside its domain, as well as allowing the process to manipulate itself or copies of itself (children). for further information refer to man pages

man 3 signal

Here you are a sample program using the signal facility.

The signal() function at the start of main() function says that if there will be a CTRL-C (SIGNINT) event the control flow shall move to the safeExit() function. This function will perform all the operations needed to perform a safe exit from the program.




  |           safeExit.c  –  description                         |

  |                ——————-                           |

  | begin      : 24/06/2011 19.00                                |

  | copyright  : ah ah ah                                        |

  | author     :                                                 |

  | email      :                                                 |

  | compiling  : gcc -o safeExit safeExit.c                      |

  |                                                              |



  | SYSTEM INCLUDES                                              |


#include <stdio.h>

#include <stdlib.h>

#include <signal.h>

#include <unistd.h>


  | PROTOTYPES                                                   |


void safeExit(int sig);

int main(int argc, char **argv);

void safeExit(int sig)


    printf("CTRL-C received, exiting program\n");



int main(int argc, char **argv)


    signal(SIGINT, &safeExit);