Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Kernel#trap

Signal.trap(signal, command) → obj
Signal.trap(signal) { ... } → obj

Specifies the handling of signals. Returns the previous handler for the given signal.

Argument signal is a signal name (a string or symbol such as SIGALRM or SIGUSR1) or an integer signal number. When signal is a string or symbol, the leading characters SIG may be omitted.

Argument command or block provided specifies code to be run when the signal is raised.

Argument command may also be a string or symbol with the following special values:

  • IGNORE, SIG_IGN: the signal will be ignored.

  • DEFAULT, SIG_DFL: Ruby’s default handler will be invoked.

  • EXIT: the process will be terminated by the signal.

  • SYSTEM_DEFAULT: the operating system’s default handler will be invoked.

The special signal name EXIT or signal number zero will be invoked just prior to program termination:

Example
Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD")  { puts "Child died" }
fork && Process.wait

Outputs:

Terminating: 27461
Child died
Terminating: 27460
See also #trace_var #untrace_var #throw #URI also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0