Ruby 线程死亡时终止shell进程

Ruby 线程死亡时终止shell进程,ruby,Ruby,我有这样的代码: #/usr/bin/env ruby Thread.report\u on\u exception=false Thread.abort\u on\u异常=true 新做的 `shellcommand 1 2 3` 结束 做其他事情吗 如果do\u other\u stuff遇到异常,它会杀死线程和整个ruby进程,这正是我想要的。但是,shell命令1 2 3继续在后台运行 当ruby进程中止时,我怎么能让shellcommand 1 2 3也被终止呢?你不能(至少在线程上

我有这样的代码:

#/usr/bin/env ruby
Thread.report\u on\u exception=false
Thread.abort\u on\u异常=true
新做的
`shellcommand 1 2 3`
结束
做其他事情吗
如果
do\u other\u stuff
遇到异常,它会杀死线程和整个ruby进程,这正是我想要的。但是,
shell命令1 2 3
继续在后台运行

当ruby进程中止时,我怎么能让
shellcommand 1 2 3
也被终止呢?

你不能(至少在
线程上有一个通用标志)。这是一个单独的进程,您从一个线程开始。线程染色不会停止该过程

您必须保存进程的pid并显式终止它:

Thread.report_on_exception = false
Thread.abort_on_exception = true

pids = []

at_exit do
  pids.each do |pid|
    `kill -9 #{pid}`
  end
end

Thread.new do
  pids.push Process.spawn('for((i=0; ;++i)); do echo "$i"; sleep 1; done')
end

sleep 5
raise 'Failure'
输出:

0
1
2
3
4
Traceback (most recent call last):
test.rb:17:in `<main>': Failure (RuntimeError)
0
1.
2.
3.
4.
回溯(最近一次呼叫最后一次):
test.rb:17:in`:失败(RuntimeError)
不用说,不要像在生产中那样使用此代码