Write a C program that does not terminate when Ctrl+C is pressed

CServer Side ProgrammingProgramming

In this section we will see how to write a program in C that cannot be terminated by the Ctrl + C key.

The Ctrl + C generates the keyboard interrupt, and it stops the execution of the current process. Here when we will press the Ctrl + C key, it will print a message then continues the execution. To use this functionality, we will use the signal handling technique in C. When the Ctrl + C is pressed it generates SIGINT signal. There are some other signals and their functionalities in the following list.

Signal
Description
SIGABRT
Indicates Abnormal termination
SIGFPE 
Indicates floating point exception
SIGILL 
Indicates invalid instruction.
SIGINT 
Indicates interactive attention request sent to the program.
SIGSEGV 
Indicates invalid memory access.
SIGTERM 
Indicates termination request sent to the program.


Here we will use the standard C library function signal() to handle these signals.

Example Code

#include <stdio.h>
#include <signal.h>
void sigint_handler(int signum) { //Handler for SIGINT
   //Reset handler to catch SIGINT next time.
   signal(SIGINT, sigint_handler);
   printf("Cannot be stopped using Ctrl+C \n");
   fflush(stdout);
}
main () {
   signal(SIGINT, sigint_handler);
   while(1) { //create infinite loop
   }
}

Output

Cannot be stopped using Ctrl+C
Cannot be stopped using Ctrl+C
raja
Published on 15-Mar-2019 10:37:44
Advertisements