Sobes.tech
Junior

What is the difference between SIGTERM and SIGKILL signals?

sobes.tech AI

Answer from AI

SIGTERM is a polite request to terminate a process. The process can catch this signal, perform cleanup (for example, save data, close connections), and exit gracefully. If the process has no handler or ignores the signal, it terminates by default.

SIGKILL is a forceful termination of a process. This signal cannot be caught, ignored, or blocked by the process. The operating system immediately stops the process without giving it a chance to perform any cleanup. It is used when the process does not respond to SIGTERM.

Here are the main differences:

Attribute SIGTERM SIGKILL
Handling capability Yes No
Graceful termination Possible (if implemented in the process) Impossible (immediate termination)
Usage Preferable for proper exit Last resort when SIGTERM fails

Example of using SIGTERM in a Python script:

import signal
import sys
import time

def terminate_handler(signum, frame):
    print(f"Received SIGTERM ({signum}). Cleaning up...")
    # Add cleanup logic here
    sys.exit(0)

print("Process started.")
signal.signal(signal.SIGTERM, terminate_handler)

try:
    while True:
        time.sleep(1)
        # Simulate work
except KeyboardInterrupt:
    print("Process interrupted by user (Ctrl+C).")
    sys.exit(0)

Examples of sending signals from the command line:

# Find the PID of the process
# ps aux | grep your_process_name

# Send SIGTERM (default kill without options)
# kill <pid>

# Send SIGKILL
# kill -9 <pid>

Overall, SIGTERM is the preferred way to terminate processes as it allows them to exit properly. SIGKILL should only be used as a last resort.