In this lesson, you will learn how the Linux kernel uses asynchronous signals to interrupt a running process and notify it of important events.
The Nature of Asynchronous Interruption
Think of a signal as a "software interrupt." In your journey through process management, you’ve learned how processes spend their time executing instructions, waiting for I/O, or shifting through different scheduling priorities. Normally, a process is oblivious to the outside world unless it explicitly asks for information. Signals break this isolation by allowing the kernel to force a process to pause its current work and handle an event immediately.
Because this happens "asynchronously," the process does not know when the signal will arrive. It could be in the middle of a complex calculation or sitting idle. When the kernel delivers a signal, it momentarily hijacks the process’s execution context, forcing it to jump to a specific instruction—often a user-defined "signal handler"—to react to the event.
How Delivery Happens
When an event occurs—such as a user pressing Ctrl+C in a terminal or a process attempting to access restricted memory—the kernel updates the destination process’s task structure to indicate a pending signal.
The delivery process follows these steps:
- Generation: The kernel identifies an event (like a hardware fault or an external request).
- Notification: The kernel marks the signal as "pending" for the target process.
- Execution: The next time the process is scheduled to run, the kernel checks for pending signals. If one exists, the kernel forces the process to stop its current flow and execute the designated signal handler.
Consider a program designed to clean up temporary files:
#include <signal.h>
#include <stdio.h>
void handle_signal(int sig) {
printf("Caught signal %d. Cleaning up files...\n", sig);
}
// The process registers the handler and then waits for events
signal(SIGINT, handle_signal);
In this snippet, when you press Ctrl+C, the kernel interrupts the program, stops its current task, and triggers handle_signal before the process even realizes it was interrupted. Once the handler completes, the process resumes exactly where it left off, unaware of the interruption.
Key Takeaway: Signals provide a mechanism for the kernel to asynchronously interrupt a process’s normal flow of execution, compelling it to respond to system events or external requests immediately.