Tag Archives: sigint
C++ || Snippet – How To Override The Default Signal Handler (CTRL-C)
The following is sample code which demonstrates the use of the “signal” function call on Unix based systems.
Signals are interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C. The “signal” function call receives two arguments. The first argument is an integer which represents the signal number, and the second argument is a pointer to the user defined signal handling function.
The following program catches the “SIGINT” signal number using the signal() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
// ============================================================================ // Author: K Perkins // Date: Oct 3, 2013 // Taken From: http://programmingnotes.org/ // File: Signal.cpp // Description: Demonstrate the use of overriding the default signal // handler for the case when the user presses Ctrl-C. Test it by // running and pressing Ctrl-C // ============================================================================ #include <iostream> #include <csignal> #include <unistd.h> using namespace std; // function prototype void SignalHandlerFunc(int arg); // global variable int count = 10; int main() { // overide the default signal handler (CTRL-C) // with our own "SignalHandlerFunc" function signal(SIGINT, SignalHandlerFunc); cerr<<"nPlease press CTRL-Cnn"; // loop until condition is met do{ sleep(1); }while(count > 0); // press ENTER on the keyboard to end // the program once all "lives" are lost cin.get(); return 0; }// end of main /** * This function handles the signal * @param arg - the signal number */ void SignalHandlerFunc(int arg) { // display text when user presses CTRL-C if(count > 0) { cerr<<" Haha I have "<<count<<" lives!n"; } else { cerr<<" ** Ahh you got me...n"; } --count; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
Please press CTRL-C
^C Haha I have 10 lives!
^C Haha I have 9 lives!
^C Haha I have 8 lives!
^C Haha I have 7 lives!
^C Haha I have 6 lives!
^C Haha I have 5 lives!
^C Haha I have 4 lives!
^C Haha I have 3 lives!
^C Haha I have 2 lives!
^C Haha I have 1 lives!
^C ** Ahh you got me...