Caveats for implementing Signal.trap callbacks

As with implementing signal handlers in C or most other languages, all code passed to Signal.trap must be reentrant. If you are not familiar with reentrancy, you need to read up on it at Wikipedia or elsewhere before reading the rest of this document.

Most importantly, “thread-safety” does not guarantee reentrancy; and methods such as Mutex#lock and Mutex#synchronize which are commonly used for thread-safety even prevent reentrancy.

An implementation detail of the Ruby VM

The Ruby VM defers Signal.trap callbacks from running until it is safe for its internal data structures, but it does not know when it is safe for data structures in YOUR code. Ruby implements deferred signal handling by registering short C functions with only async-signal-safe functions as signal handlers. These short C functions only do enough tell the VM to run callbacks registered via Signal.trap later in the main Ruby Thread.

Unsafe methods to call in Signal.trap blocks

When in doubt, consider anything not listed as safe below as being unsafe.

Commonly safe operations inside Signal.trap blocks

System call wrapper methods which are safe inside Signal.trap

Since Ruby has wrappers around many async-signal-safe C functions the corresponding wrappers for many IO, File, Dir, and Socket methods are safe.

(Incomplete list)