线程死亡时杀死Shell进程

时间:2019-10-29 15:29:46

标签: ruby

我有这样的代码:

let file = fs.createWriteStream(`${movie.id}`.jpg)

如果#! /usr/bin/env ruby Thread.report_on_exception=false Thread.abort_on_exception=true Thread.new do `shellcommand 1 2 3` end do_other_stuff 遇到异常,它将杀死线程和整个ruby进程,这正是我想要的。但是,do_other_stuff继续在后台运行。

当红宝石流程中止时,我怎么也shellcommand 1 2 3被杀死?

1 个答案:

答案 0 :(得分:1)

不能(至少在Thread上带有通用标志)。这是您在线程中启动的独立过程。线程死亡不会停止进程。

您必须保存该进程的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)

不用说,不要像在生产中那样使用此代码。