ruby - 当线程死亡时杀死 shell 进程

标签 ruby

我有这样的代码:

#! /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

如果 do_other_stuff 遇到异常,它会杀死线程和整个 ruby​​ 进程,这正是我想要的。但是,shellcommand 1 2 3 继续在后台运行。

当 ruby​​ 进程中止时,如何让 shellcommand 1 2 3 也被杀死?

最佳答案

你不能(至少在 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)

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

关于ruby - 当线程死亡时杀死 shell 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58610588/

相关文章:

ruby-on-rails - Rails 410 没有路线匹配

Ruby 关键字作为命名哈希参数

ruby - 有没有比解析 ls 输出更好的方法来读取 Ruby 中的 ACL?

ruby - 如何验证内容是否变灰

ruby - 在 Ruby Shoes 上加载字体

ruby - Ruby 1.9.2 中机架级别的 SystemStackError,而不是 1.8.7

Ruby Sinatra - 在 mongoHQ 上连接到 mongoDB 失败

ruby-on-rails - 如何使用 %20 编码在 Ruby 中形成 URI

RUBY:如何匹配散列中的零值

ruby-on-rails - 选择总是返回 :id even if it is not included in the call