Skip to content
instance method

Kernel#fork

() -> ::Integer?
() { () -> void } -> ::Integer
Process.fork { ... } → integer or nil
Process.fork → integer or nil

Creates a child process.

With a block given, runs the block in the child process; on block exit, the child terminates with a status of zero:

Example
puts "Before the fork: #{Process.pid}"
fork do
  puts "In the child process: #{Process.pid}"
end                   # => 382141
puts "After the fork: #{Process.pid}"

Output:

Example
Before the fork: 420496
After the fork: 420496
In the child process: 420520

With no block given, the fork call returns twice:

  • Once in the parent process, returning the pid of the child process.

  • Once in the child process, returning nil.

Example:

Example
puts "This is the first line before the fork (pid #{Process.pid})"
puts fork
puts "This is the second line after the fork (pid #{Process.pid})"

Output:

Example
This is the first line before the fork (pid 420199)
420223
This is the second line after the fork (pid 420199)

This is the second line after the fork (pid 420223)

In either case, the child process may exit using Kernel.exit! to avoid the call to Kernel#at_exit.

To avoid zombie processes, the parent process should call either:

The thread calling fork is the only thread in the created child process; fork doesn’t copy other threads.

Note that method fork is available on some platforms, but not on others:

Example
Process.respond_to?(:fork) # => true # Would be false on some.

If not, you may use ::spawn instead of fork.

See also #Float #format #fail #frozen? also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0