你如何在 Ruby 中生成子进程? [英] How do you spawn a child process in Ruby?

查看:45
本文介绍了你如何在 Ruby 中生成子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将主进程中的代码块卸载到子进程以使其并发运行.我还想拥有生成的子进程的 PID,以便在必要时监控和终止它.

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.

推荐答案

您可以使用 fork 内核方法.下面是一个例子:

You can use the fork kernel method. Here is an example:

#!/usr/bin/env ruby
puts "This is the master process."

child_pid = fork do
  puts "This is the child process"
  exit
end

puts "The PID of the child process is #{child_pid}"

fork 方法返回它派生的进程的 PID,并执行传递的块中的任何代码.像普通的 Ruby 块一样,它保持父进程的绑定.

The fork method returns the PID of the process it forks and executes any code in the block passed. Like regular Ruby blocks it keeps the bindings of the parent process.

让你的分叉进程exit是个好主意.

It is a good idea to make your forked process exit.

这篇关于你如何在 Ruby 中生成子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆