Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Signal Handling Tutorial – Manage OS Signals with signal Module

Python Signal Handling

When Python programs run, the operating system may send signals to them.

Signals are used to:

  • Interrupt a program
  • Terminate a process
  • Notify events
  • Handle system-level communication

Python provides the signal module to handle these signals gracefully.


What is a Signal?

A signal is a software interrupt sent by the operating system to a process.

Examples:

  • Ctrl + C (Keyboard Interrupt)
  • System shutdown request
  • Process termination request

Common Signals in Python

SignalDescription
SIGINTInterrupt from keyboard (Ctrl + C)
SIGTERMTermination signal
SIGKILLForce kill process
SIGALRMAlarm signal
SIGSTOPStop process

1. Basic Signal Handling

Python provides the signal module.

import signal
import time

2. Handling SIGINT (Ctrl + C)

import signal
import time

def handler(signum, frame):
    print("Signal received:", signum)

signal.signal(signal.SIGINT, handler)

while True:
    print("Running...")
    time.sleep(1)

Output (on Ctrl + C)

Signal received: 2

3. Default Signal Behavior

If no handler is defined:

  • SIGINT → program stops
  • SIGTERM → program terminates

4. Handling SIGTERM

import signal
import time

def handler(signum, frame):
    print("Graceful shutdown triggered")

signal.signal(signal.SIGTERM, handler)

while True:
    time.sleep(1)

5. Custom Signal Handler

def custom_handler(signum, frame):
    print(f"Handled signal: {signum}")

Registering Handler

signal.signal(signal.SIGINT, custom_handler)

6. Ignoring Signals

You can ignore signals using signal.SIG_IGN.

signal.signal(signal.SIGINT, signal.SIG_IGN)

Now Ctrl + C will be ignored.


7. Restoring Default Behavior

signal.signal(signal.SIGINT, signal.SIG_DFL)

8. Signal with Logging

import logging
import signal

logging.basicConfig(level=logging.INFO)

def handler(signum, frame):
    logging.info(f"Signal received: {signum}")

signal.signal(signal.SIGINT, handler)

9. Graceful Shutdown Example

import signal
import time

running = True

def stop_handler(signum, frame):
    global running
    print("Stopping program...")
    running = False

signal.signal(signal.SIGINT, stop_handler)

while running:
    print("Working...")
    time.sleep(1)

print("Program exited safely")

10. Alarm Signal (SIGALRM)

Used for time-based interrupts.

import signal

def alarm_handler(signum, frame):
    print("Alarm triggered!")

signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(3)

Output

Alarm triggered!

11. Signal Flow in Python

OS → Signal → Python Process → Signal Handler → Action

12. Real-World Use Cases

Signal handling is used in:

  • Web servers
  • Background services
  • Long-running scripts
  • Daemon processes
  • System utilities

13. Example: Server Shutdown Handler

import signal

def shutdown(signum, frame):
    print("Shutting down server...")

signal.signal(signal.SIGTERM, shutdown)

14. Best Practices

  • Always use graceful shutdown handlers
  • Avoid heavy processing inside signal handlers
  • Use logging instead of print in production
  • Restore default behavior when needed
  • Keep handlers simple and fast

15. Common Mistakes

Blocking inside handler

def handler(signum, frame):
    while True:
        pass

❌ This can freeze the program


Ignoring important signals

Ignoring SIGTERM in production is unsafe.


Summary

Python signal handling allows programs to respond to operating system events such as interrupts and termination requests. By using the signal module, developers can build robust applications that shut down safely and handle system-level events efficiently.


Conclusion

Signal handling is essential for building production-ready Python applications. It enables graceful shutdowns, better resource management, and improved reliability in real-world systems like servers and background services.




Post a Comment

0 Comments