Kernel#fork
fork -> integer or nil Returns:
Integer or nil · Updated March 13, 2026 · Kernel Methods processes parallel multiprocessing child
The fork method creates a new process by duplicating the current process. The child process gets a copy of all memory, while the parent receives the child’s process ID.
Basic Usage
pid = fork do
# This runs in child process
puts "Child process: #{Process.pid}"
end
# This runs in parent
puts "Parent: #{Process.pid}, Child PID: #{pid}"
# Wait for child
Process.wait(pid)
Practical Examples
Parallel Processing
tasks = [1, 2, 3, 4]
tasks.each do |task|
fork do
# Process task in parallel
result = process(task)
File.write("result_#{task}.txt", result)
end
end
# Wait for all children
Process.waitall
Creating Worker Pool
def spawn_workers(count)
count.times do |i|
fork do
loop do
job = get_next_job
process_job(job) if job
end
end
end
end
Daemon Process
def daemonize
fork do
Process.setsid # New session
fork do
Dir.chdir("/")
File.umask(0000)
STDIN.reopen("/dev/null")
STDOUT.reopen("/dev/null", "a")
STDERR.reopen("/dev/null", "a")
run_daemon
end
exit!
end
Process.waitall
end
With Block
# Block version - runs block in child
fork do
puts "Child: #{Process.pid}"
end
puts "Parent: #{Process.pid}"
Handling Child Exit
# Parent can wait for specific child
pid = fork { sleep 1 }
Process.wait(pid)
puts "Child finished"
# Non-blocking check
pid = fork { }
if Process.waitpid(pid, Process::WNOHANG)
puts "Child done"
end
Exit Status
pid = fork { exit(42) }
_, status = Process.wait2(pid)
puts status.exitstatus # => 42
Important Notes
Resource Management
# Children inherit file descriptors
# Close what you don't need
child = fork do
STDIN.close
# ...
end
Copy-on-Write
# Modern OS uses copy-on-write
# Parent and child share memory until modified
# Efficient for read-heavy tasks
On Platforms Without Fork
# On Windows, fork not available
# Use spawn instead
spawn("ruby", "script.rb")
Comparison with Threads
# fork - separate processes, no GIL
# threads - same process, shared memory