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.
The fork() system call creates a “copy” of the current process. For our purposes in Ruby, it enables arbitrary code to run asynchronously.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With