gpt4 book ai didi

ruby - 如何在停止时杀死 ruby​​ Thor 中的所有进程?

转载 作者:数据小太阳 更新时间:2023-10-29 07:19:55 25 4
gpt4 key购买 nike

我在下面使用 Thor 编写了一个脚本像管理 ARGV 的 rake 任务一样运行。

#!/usr/bin/env ruby
require "thor"

class Run < Thor

desc "start", "start script"
def start
p1 = fork{ loop... }
p2 = fork{ loop... }

# 3 processes running

Process.detach(p1)
Process.waitpid(p1)

end

desc "stop", "stop script"
def stop
# kill all 3 pids
end

end

Run.start

当启动 ruby script.rb start 时,它会生成两个子进程(总共三个)。我的问题是如何在执行 ruby script.rb stop 时终止所有进程。我在网上看到,开始时,我应该将 pid 父进程存储到一个文件中,停止时,我读取它并杀死它。问题是杀死 parent 并不会杀死 child 。所以我可以将所有三个 pid 保存在文件中,稍后一个一个地杀死。

我在问自己什么是正确的方法,以及我在 start 中处理进程的方式是否正确。

最佳答案

如果你知道你 parent 的 pid,你可以像这样找到并杀死所有的 child :

# Find child pids, works on Linux / OSX
def child_pids(pid)
pipe = IO.popen("ps -ef | grep #{pid}")
pipe.readlines.map do |line|
parts = line.strip.split(/\s+/)
parts[1].to_i if parts[2] == pid.to_s and parts[1] != pipe.pid.to_s
end.compact
end

# kill -9 every child
child_pids(parent_pid).each { |pid| Process.kill('TERM', pid) }

关于ruby - 如何在停止时杀死 ruby​​ Thor 中的所有进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15278862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com