Kernel#exit!

exit!(status = false)
Returns: Never returns · Updated March 13, 2026 · Kernel Methods
process exit termination status

The exit! method terminates the Ruby process immediately without running any cleanup code. Unlike exit, it does not run at_exit handlers or ensure finalizers.

Basic Usage

# Exit with default code 1
exit!

# Exit with specific code
exit!(0)  # Success
exit!(1)  # Error
exit!(2)  # Another error code

How It Differs from exit

# exit - runs at_exit handlers
at_exit { puts "Cleaning up..." }
exit
# Output: Cleaning up...

# exit! - immediate termination
at_exit { puts "Cleaning up..." }
exit!
# No output - exits immediately

Practical Examples

Fork Safety

# In parent process after fork
if fork.nil?
  # Child process
  # Exit immediately without running parent's at_exit
  exit!
end

Timeout Handling

# Kill process after timeout
begin
  Timeout.timeout(5) do
    long_running_task
  end
rescue Timeout::Error
  # Force exit without cleanup
  exit!(1)
end

Signal Handling

trap(:KILL) { exit! }  # Cannot trap KILL anyway
trap(:TERM) { exit!(1) }  # Force TERM to exit immediately

Testing

# Exit child in tests without running other code
def run_test_case(test)
  fork do
    begin
      test.run
    rescue => e
      puts "Test failed: #{e}"
      exit!(1)
    end
  end
end

Exit Codes

exit!(0)   # Success
exit!(1)   # General error
exit!(2)   # Misuse of command
exit!(126) # Command not executable
exit!(127) # Command not found
exit!(128) # Invalid exit argument

When to Use exit!

  • After fork to avoid double at_exit runs
  • When you need guaranteed immediate termination
  • In signal handlers where cleanup isn’t desired
  • Performance-critical code where cleanup overhead matters

When NOT to Use exit!

  • Normal application termination (use exit)
  • When you need cleanup code to run
  • In daemons that need to flush buffers
  • When at_exit handlers contain important cleanup

See Also