πŸ’‘ Advanced Python Concepts
Estimated reading: 4 minutes 39 views

πŸ“Ά Python Signal Handling – Graceful Shutdown with SIGINT, SIGTERM

🧲 Introduction – Why Handle Signals in Python?

Signals are a core part of Unix-based systems. They allow the OS or other processes to notify your program about events such as:

  • Ctrl+C (interrupt via SIGINT)
  • Termination (SIGTERM)
  • Hang-up (SIGHUP)
  • Child process events (SIGCHLD)

With Python’s built-in signal module, you can intercept and handle these events to:

  • Shutdown cleanly
  • Save state before exit
  • Restart services automatically
  • Handle timeouts or inter-process communication

🎯 In this guide, you’ll learn:

  • What signals are and how they work in Python
  • How to catch signals like SIGINT and SIGTERM
  • How to safely clean up resources using signal handlers
  • Best practices and limitations of signal handling

βœ… What Is a Signal?

A signal is a software interrupt sent to a process to notify it of an event (e.g., kill signal, interrupt signal).

In Python, you can register handlers that are executed when a signal is received.


πŸ”§ Setting Up a Signal Handler

βœ… Basic Signal Handler Example

import signal
import sys

def handle_sigint(signum, frame):
    print("Caught SIGINT (Ctrl+C). Exiting gracefully...")
    sys.exit(0)

signal.signal(signal.SIGINT, handle_sigint)

while True:
    pass  # Keep running

βœ… Pressing Ctrl+C will now trigger the handler and exit cleanly.


πŸ“¦ Supported Signals (Common)

SignalMeaning
SIGINTInterrupt from keyboard (Ctrl+C)
SIGTERMTerminate program (graceful shutdown)
SIGHUPHang-up (e.g., terminal closed)
SIGCHLDChild process status changed
SIGALRMAlarm signal
SIGUSR1/2Custom user-defined signals

πŸ§ͺ Example – Handle SIGTERM

def handle_sigterm(signum, frame):
    print("Caught SIGTERM. Cleaning up...")
    sys.exit(0)

signal.signal(signal.SIGTERM, handle_sigterm)

βœ… Useful in Docker containers, daemonized apps, or system services.


🧠 Signal Parameters

The signal handler always accepts two arguments:

def handler(signum, frame):
    print(f"Signal received: {signum}")
  • signum: signal number (e.g., 2 for SIGINT)
  • frame: current stack frame (useful for debugging)

πŸ› οΈ Using signal.SIGALRM for Timeouts

import time

def timeout_handler(signum, frame):
    raise TimeoutError("Operation timed out!")

signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(3)  # Set a 3-second timer

try:
    time.sleep(5)  # This will be interrupted
except TimeoutError as e:
    print(e)

βœ… Raises a TimeoutError after 3 seconds.


πŸ“΅ Limitations of Signal Handling in Python

LimitationDetails
Works only in main threadHandlers won’t run in background threads
Can’t catch SIGKILL, SIGSTOPThese signals are uncatchable
Handlers must be fastAvoid blocking or long-running logic

🧰 Real-World Use Case – Graceful Shutdown

import time

running = True

def handle_exit(signum, frame):
    global running
    print("Shutdown signal received.")
    running = False

signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGTERM, handle_exit)

print("Running... Press Ctrl+C to stop.")
while running:
    time.sleep(1)

print("Clean exit complete.")

πŸ’‘ Ideal for cleanup scripts, cron jobs, long-running services.


πŸ“˜ Best Practices

βœ… Do This❌ Avoid This
Register signals early in the programDelaying signal setup after startup
Handle SIGINT and SIGTERM togetherIgnoring SIGTERM in production apps
Use flags (not direct exits) for long loopsExiting mid-process in multithreaded apps
Keep handlers lightweightRunning heavy logic or blocking operations

πŸ“Œ Summary – Recap & Next Steps

Python signal handling allows you to gracefully manage external interrupts and control how your application shuts down or responds to external events.

πŸ” Key Takeaways:

  • βœ… Use signal.signal() to register signal handlers
  • βœ… Handle SIGINT, SIGTERM, and SIGHUP for clean shutdowns
  • βœ… Signals only affect the main thread
  • βœ… Use signal.alarm() to implement timeouts

βš™οΈ Real-World Relevance:
Used in system daemons, CLI tools, Docker containers, and supervised services like Gunicorn, Celery, or custom schedulers.


❓ FAQ – Python Signal Handling

❓ Can Python catch Ctrl+C?

βœ… Yes. Use signal.SIGINT to handle keyboard interrupts.

❓ Can I handle signals in threads?

❌ No. Signal handlers only work in the main thread.

❓ How do I stop a long-running loop using signals?

βœ… Set a global flag in the handler and check it inside the loop.

❓ What signals can’t be handled?

  • SIGKILL (9)
  • SIGSTOP (19)

These cannot be caught or ignored.

❓ What’s the difference between SIGINT and SIGTERM?

  • SIGINT: Sent by keyboard (Ctrl+C)
  • SIGTERM: Sent by system/process, often to gracefully stop a program

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Signal Handling

Or Copy Link

CONTENTS
Scroll to Top