我想将我的主进程中的一块代码卸载到子进程中,以使其并发运行。我还想获得生成的子进程的PID,以便在必要时对其进行监视和终止。
在Ruby中如何生成子进程?
原标题:
最佳回答
您可以使用 fork
内核方法。 这是一个例子:
#!/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块一样,它保留父进程的绑定。
将您的分叉进程退出
是一个好主意。
问题回答
除了Chris的好回答之外,请记得从您的主进程中调用Process.wait
以回收您的子进程,否则您将留下僵尸进程。
如评论中所请求的示例:
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"
In 1.9 you can use Process.spawn command. See also http://en.wikibooks.org/wiki/Ruby_Programming/Running_Multiple_Processes
如果您愿意使用线程而不是进程,那么像这样的东西可能更具可扩展性,可以扩展到多个分支:
def doit(x)
sleep(rand(10))
puts "Done... #{x}"
end
thingstodo = ["a","b","c","d","e","f","g"]
tasklist = []
# Set the threads going
thingstodo.each { |thing|
task = Thread.new(thing) { |this| doit(this) }
tasklist << task
}
# Wait for the threads to finish
tasklist.each { |task|
task.join
}
请查看下面John Topley的优秀评论和参考,关于Ruby执行模型及其限制。
刚刚编辑了一下,以更正一个明显的错误(未分配任务),并按照@(Jason King)的建议行事。
相关问题
热门标签
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding