Process forking lets a program do many things at the same time by creating copies of itself. This helps finish tasks faster.
Process forking for parallelism in Ruby
pid = fork do # code to run in the child process end Process.wait(pid) # wait for the child process to finish
The fork method creates a new child process.
The block after fork runs only in the child process.
pid = fork do puts "Child process running" end Process.wait(pid) puts "Parent process finished"
pid = fork do # Child does nothing end Process.wait(pid) puts "Child done"
pid = fork do puts "Child start" sleep 2 puts "Child end" end puts "Parent continues" Process.wait(pid)
This program shows the parent process creating a child process. The child prints messages and sleeps for 1 second to simulate work. The parent waits for the child to finish before exiting.
puts "Parent process ID: #{Process.pid}" pid = fork do puts "Child process ID: #{Process.pid}" puts "Child is working..." sleep 1 puts "Child finished work" end puts "Parent is waiting for child to finish" Process.wait(pid) puts "Child process has finished. Parent exiting."
Time complexity depends on the tasks inside the child process, but forking itself is fast.
Space complexity increases because the child process is a copy of the parent.
Common mistake: forgetting to wait for child processes, which can cause zombie processes.
Use forking when tasks are independent and can run at the same time. Use threads if tasks share memory and need communication.
Forking creates a new process to run code in parallel.
The child process runs the block given to fork.
The parent can wait for the child to finish using Process.wait.