C program that does not suspend when Ctrl+Z is pressed

In C programming, when a program malfunctions or runs indefinitely, programmers can explicitly stop execution using keyboard shortcuts. Understanding how to handle or override these signals is crucial for creating robust applications.

There are two primary keyboard shortcuts used to control program execution −

  • Ctrl+C − Sends a SIGINT signal to terminate the program immediately. This signal can be handled using the signal() function in C.
  • Ctrl+Z − Sends a SIGTSTP signal to suspend the program execution. This signal is more powerful and can also be intercepted and handled.

Here, we will create a C program that intercepts the Ctrl+Z signal and prevents suspension by displaying a custom message instead.

Syntax

#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);

Example: Handling SIGTSTP Signal

This program demonstrates how to override the default Ctrl+Z behavior using a custom signal handler −

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void signalHandler(int sig_num) {
    signal(SIGTSTP, signalHandler);
    printf("\nCtrl+Z cannot suspend this program!<br>");
    printf("Press Ctrl+C to terminate.<br>");
}

int main() {
    int counter = 0;
    
    signal(SIGTSTP, signalHandler);
    printf("Program started. Try pressing Ctrl+Z...<br>");
    
    while(counter < 20) {
        printf("Running... %d<br>", counter);
        sleep(1);
        counter++;
    }
    
    printf("Program completed normally.<br>");
    return 0;
}
Program started. Try pressing Ctrl+Z...
Running... 0
Running... 1
Running... 2
^ZCtrl+Z cannot suspend this program!
Press Ctrl+C to terminate.
Running... 3
Running... 4
Program completed normally.

How It Works

  • The signal(SIGTSTP, signalHandler) function registers our custom handler for the SIGTSTP signal.
  • When Ctrl+Z is pressed, instead of suspending, the program calls signalHandler().
  • The handler re-registers itself and displays a message, allowing the program to continue execution.
  • The program runs for 20 iterations and then terminates normally.
Note: This example works on Unix-like systems (Linux, macOS). Signal handling behavior may vary on different operating systems.

Key Points

  • Signal handlers must re-register themselves in some implementations for persistent behavior.
  • SIGTSTP (terminal stop) is the signal sent by Ctrl+Z.
  • Custom signal handling allows programs to gracefully manage interruption attempts.

Conclusion

By using the signal() function, C programs can intercept and handle system signals like SIGTSTP. This technique is valuable for creating applications that need to perform cleanup operations or prevent accidental suspension during critical tasks.

Updated on: 2026-03-15T12:04:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements