Warning at exit handlers are inherited from parent processes

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the ruby category.

Last Updated: 2024-04-25

When I ran a big fat binary called gotty via a forked system call in ruby, the natural termination of this forked process had the unexpected effect of killing the parent process, the web-server Sinatra.

Here is roughly the code I used gotty:

fork do
  system("gotty ...")
end

Why did this happen? Sinatra had added its own at_exit handlers that caused a full shutdown, and at_exit handlers are inherited in Ruby. My forked process inherited these from the parent Sinatra processes. This caused the premature termination.

Solution:

A child process can exit using Kernel.exit! to avoid running any at_exit functions.

Therefore override at_exit in the fork with this version:

fork do
  at_exit { exit! }
  system("gotty ...")
end