Write a C console app that does not exit on Ctrl+C press

C program to make a console app that does not terminate when Ctrl+C is pressed

Ctrl+C in the command line and GUI

Ctrl+C is a common shortcut used by most popular operating systems for copying a portion of selected text and files in the graphical user interface mode or desktop environment mode. But there is another common action happen for pressing Ctrl+C in the command line or terminal interface.

Probably in the terminal or command line environment, when Ctrl+C is pressed, a running program exits. In this article, we will write a C program that won’t be terminated even after pressing the common shortcut Ctrl+C for terminating a program in a terminal.

Think about the problem

When we press any key or combination of keys on the keyboard, probably we send a certain signal to the machine for each key and combination. And for the signal that is sent by Ctrl+C, is to exit a running program in the terminal interface. Because for that certain signal, the running program exiting function is pre-programmed.

So to prevent this, we have to modify the system function for that certain signal or we have to overtake the system function with our own function. In this case, we will print, “Program can’t be terminated by Ctrl+C”.

Solving using C program

C provides a signal detecting standard library in the signal.h header file. So we can use the signal library to detecting the signal of Ctrl+C and change its action for printing the message “Program can’t be terminated by pressing Ctrl+C”. See below, how can we do that;

Program analysis

At first, we included the signal header file for accessing the signal detecting macros and function in our program. For signal detection, we will use SIGINT signal function. we have used the signal function using the SIGINT constructor with the signal handler function name as signalHandler.

Now when we will press the Ctrl+C then the signal will be sent to signalHandller function. In the signalHandler function, we have used the same signal statement to catch the signal. After catching the signal, the rest of the code of the signalHandler function will be executed and then will back to the main function again.