How to Fork a Process in Ruby

Thu, Jul 4, 2019

Read in 1 minutes

Forking in Ruby is pretty straight forward. It pretty much mimicks the c version in that the same system calls need to be called, and they are named the same in Ruby as in C. The difference in this code is pretty much down to the fact that Ruby is a dynamic language (so we do not have to think about types) and that we do not need to import anything for fork to work.

Where we in C need to know whether we are in the forked code or not - Ruby handles this using a block. The block only executes for the child process - the parent process just returns the pid.

4.times do |count|

  pid = fork do
    puts "Child #{count} started"
    sleep(5)
  end

  puts "Started child with PID #{pid}"
end

Process.wait

puts "All children stopped"

run it with ruby fork.rb

See Also

How to Fork a Process in C

Wed, Jul 3, 2019

Read more →

How to Write Json in Ruby

Fri, Sep 11, 2015

Read more →

How to Parse Json in Ruby

Thu, Sep 10, 2015

Read more →

How to Read from stdin in Ruby

Fri, Aug 28, 2015

Read more →

How to Write a TCP Echo Server in Ruby

Mon, Aug 24, 2015

Read more →