Kernel#trap

trap(signal, handler) -> handler
Returns: Object · Updated March 13, 2026 · Kernel Methods
signals processes handlers interrupts

The trap method registers a handler for operating system signals. Signals are notifications sent to your process by the OS or other processes, commonly used for graceful shutdown and handling interrupts.

Common Signals

# INT - Interrupt (Ctrl+C)
trap(:INT) { puts "Interrupted!" }

# TERM - Termination request
trap(:TERM) { puts "Shutting down..." }

# KILL - Immediate termination (cannot trap)
# trap(:KILL) { }  # Doesn't work!

# HUP - Hangup (often used for config reload)
trap(:HUP) { load_config }

# USR1, USR2 - User-defined signals
trap(:USR1) { do_custom_action }

Handler Types

Block Handlers

# Block as handler
trap(:INT) do
  puts "\nStopping gracefully..."
  exit 0
end

String Handlers

# Built-in handler names
trap(:INT, "IGNORE")  # Ignore the signal
trap(:INT, "DEFAULT") # Default behavior
trap(:INT, "EXIT")    # Exit immediately

Method Handlers

def handle_signal
  cleanup
  exit
end

trap(:INT, method(:handle_signal))

Practical Examples

Graceful Shutdown

shutdown_requested = false

trap(:INT) { shutdown_requested = true }
trap(:TERM) { shutdown_requested = true }

loop do
  break if shutdown_requested
  process_requests
  sleep 1
end

puts "Graceful shutdown complete"

Config Reload

trap(:HUP) do
  puts "Reloading configuration..."
  load_config
  puts "Configuration reloaded"
end

Signal-Based Communication

# Parent sends signal to child
child_pid = fork do
  trap(:USR1) { puts "Got signal!"; exit }
  sleep
end

Process.kill(:USR1, child_pid)
Process.wait(child_pid)

Ignoring Signals

# Ignore SIGCHLD (prevent zombie processes)
trap(:CHLD, "IGNORE")

# Or for specific operations
trap(:INT, "IGNORE")  # Ctrl+C does nothing

Process Groups

# Send to process group
Process.kill(:TERM, 0)  # Signal all processes in group

Important Notes

# KILL and STOP cannot be trapped
trap(:KILL, "IGNORE")  # Still kills the process!

Ruby Signal Names

# Use symbols or strings
trap(:INT) {}
trap("INT") {}
trap(Signal.list["INT"]) {}

Thread Safety

# Signals are delivered to the main thread
# Ensure your handler is thread-safe

The trap method is essential for building robust servers and daemons that respond gracefully to operating system signals.

See Also