Course contentsShow
← Python
Lesson 1012 of 1,06016. Capstone and AutomationFree lesson

Handling Signals and Graceful Process Termination

Implement signal handling to ensure your CLI application cleans up resources and exits gracefully when users interrupt execution.

In this lesson, you will learn how to intercept system signals to ensure your CLI application performs essential cleanup before exiting.

The Problem with Harsh Terminations

When a user presses Ctrl+C or a system process manager stops your application, the operating system sends a signal (like SIGINT or SIGTERM) that abruptly halts execution. If your script is currently writing to a database, holding an open file handle, or syncing a remote data pipeline, an abrupt kill can leave your system in an inconsistent state or corrupt your data files.

Implementing Signal Handling

Python’s signal module allows you to register a "callback" function that runs the moment the OS notifies your program to shut down. Instead of dying instantly, your program pauses, executes your cleanup logic (e.g., closing connections, deleting temporary files), and then exits intentionally.

Here is how to implement a graceful exit handler:

import signal
import sys
import time

def graceful_exit(signum, frame):
    print("\nSignal received! Cleaning up resources...")
    # Add your cleanup logic here: closing DBs, flushing logs, etc.
    sys.exit(0)

# Register the handler for Keyboard Interrupt (Ctrl+C)
signal.signal(signal.SIGINT, graceful_exit)

print("Application running. Press Ctrl+C to stop.")
try:
    while True:
        time.sleep(1)
except Exception as e:
    print(f"Unexpected error: {e}")

Best Practices for Cleanup

When designing your graceful_exit function, keep it lean. Since the process is already in the middle of being terminated, avoid complex logic that might trigger new errors or hang indefinitely. The goal is simply to release external resources and log the termination event. By catching these signals, you transform your CLI tool from a "crash-prone script" into a professional-grade utility that respects the integrity of the data it handles.

Key Takeaway: Use the signal module to intercept termination requests, ensuring your application preserves data integrity by performing cleanup tasks before closing.