13 August 2013


by mo

The man page on my systems describes the fork call like this:

fork() creates a new process by duplicated the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for …

Here’s an example using ruby

  def forking()
    file = File.open('/dev/null')

    pid = Process.fork do
      p "file descriptor from child ##{Process.pid} is: #{file.fileno}"
      p "CLOSED? in #{Process.pid}: #{file.closed?}"
    p "file descriptor from master ##{Process.pid} is: #{file.fileno}"
    p "CLOSED? in #{Process.pid}: #{file.closed?}"


When a process is forked the file descriptors in the parent process are shared with the child process. When I run this example this is the output:

λ ruby forking.rb 
"file descriptor from child #21710 is: 7"
"CLOSED? in 18496: true"
"file descriptor from master #21707 is: 7"
"CLOSED? in 18494: false"

This shows that the child process has a separate process id from the parent process and that when a file descriptor is closed in the child process it does not affect the parent process.

When I run pstree on the parent process I get something like the following output:

λ pstree -p 21707

ps shows:

mo       21707  0.0  0.0  32376  6468 pts/6    Sl+  20:45   0:00 ruby forking.rb
mo       21710  0.0  0.0  32376  4652 pts/6    Sl+  20:45   0:00 ruby forking.rb

This shows two processes with two different process id’s. One for the parent process (21707) and one for the child process (21710). They also both belong to the same process group (32376).


unix 💎