How do you spawn a child process in Ruby?

前端 未结 5 449
南旧
南旧 2020-12-13 12:54

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

5条回答
  •  误落风尘
    2020-12-13 13:48

    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"
    

提交回复
热议问题