Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you spawn a child process in Ruby?

Tags:

ruby

I want to offload a block of code in my main process to child process to make it run concurrently. I also want to have the PID of the spawned child process so I can monitor and kill it if necessary.

like image 362
Chris Lloyd Avatar asked Nov 20 '08 22:11

Chris Lloyd


People also ask

What is fork in Ruby?

The fork() system call creates a “copy” of the current process. For our purposes in Ruby, it enables arbitrary code to run asynchronously.

How does child process work?

Child Process: A child process is created by a parent process in an operating system using a fork() system call. A child process may also be known as subprocess or a subtask. A child process is created as a copy of its parent process. The child process inherits most of its attributes.

What is a process in Ruby?

A Ruby Process is the instance of an application or a forked copy. In a traditional Rails application, each Process contains all the build up, initialization, and resource allocation the app will need.


1 Answers

In addition to Chris' great answer, remember to call Process.wait from your master in order to reap your child process, else you'll leave zombies behind.

Example as requested in comments:

pid = Process.fork do   puts "child, pid #{Process.pid} sleeping..."   sleep 5   puts "child exiting" end  puts "parent, pid #{Process.pid}, waiting on child pid #{pid}" Process.wait puts "parent exiting" 
like image 151
Martin Carpenter Avatar answered Sep 29 '22 19:09

Martin Carpenter