Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a C program that does not terminate when Ctrl+C is pressed
In C, we can create a program that does not terminate when Ctrl+C is pressed by using signal handling. The Ctrl+C key combination generates the SIGINT (Signal Interrupt) signal, which normally terminates a running process. However, we can intercept this signal using the signal() function and define custom behavior instead.
Syntax
#include <signal.h> void (*signal(int sig, void (*func)(int)))(int);
Where sig is the signal number and func is the handler function to be called when the signal is received.
Common Signal Types
| 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 |
Example: Handling SIGINT Signal
This program demonstrates how to intercept Ctrl+C and continue execution −
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void sigint_handler(int signum) {
printf("\nCannot be stopped using Ctrl+C<br>");
fflush(stdout);
/* Re-register the signal handler for next occurrence */
signal(SIGINT, sigint_handler);
}
int main() {
/* Register the signal handler */
signal(SIGINT, sigint_handler);
printf("Program started. Try pressing Ctrl+C<br>");
printf("Press Ctrl+Z to stop this program<br>");
/* Infinite loop to keep program running */
while(1) {
printf("Running... (Press Ctrl+C to test)<br>");
sleep(2); /* Pause for 2 seconds */
}
return 0;
}
Output
Program started. Try pressing Ctrl+C Press Ctrl+Z to stop this program Running... (Press Ctrl+C to test) Running... (Press Ctrl+C to test) ^C Cannot be stopped using Ctrl+C Running... (Press Ctrl+C to test) ^C Cannot be stopped using Ctrl+C Running... (Press Ctrl+C to test)
How It Works
- The
signal(SIGINT, sigint_handler)function registers our custom handler for the SIGINT signal - When Ctrl+C is pressed, instead of terminating, the program calls
sigint_handler() - The handler prints a message and re-registers itself for future SIGINT signals
- The program continues running in the infinite loop
Note: This program requires a Unix-like system (Linux, macOS) to compile and run properly. On Windows, you may need to use alternative signal handling methods.
Conclusion
By using the signal() function, we can intercept system signals like SIGINT and define custom behavior. This technique is useful for creating robust applications that need graceful shutdown procedures or should not be accidentally terminated.
