【问题标题】:Waiting for Ruby child pid to exit等待 Ruby 子 pid 退出
【发布时间】:2012-09-16 08:29:18
【问题描述】:

我正在尝试 fork 一个子进程,等待它完成,如果它在一定时间内没有完成,就杀死它。

这是我目前所拥有的:

servers.each do |server|
    pid = fork do
        puts "Forking #{server}."
        output = "doing stuff here"
        puts output
    end

    Process.wait
    puts "#{server} child exited, pid = #{pid}"
end

在 Process.wait 之后/附近的某个地方,我希望某种实用程序等待 20 秒,如果该进程仍然存在,我想将其终止并将输出标记为“错误”。

我是 fork/exec 的新手。我的代码实际上分叉有效,但我只是不知道如何处理它的等待/杀死方面。

【问题讨论】:

    标签: ruby fork


    【解决方案1】:

    使用Timeout module:(代码来自http://www.whatastruggle.com/timeout-a-subprocess-in-ruby

    require 'timeout'
    
    servers.each do |server|
        pid = fork do
            puts "Forking #{server}."
            output = "doing stuff here"
            puts output
        end
    
        begin
            Timeout.timeout(20) do
                Process.wait
            end
        rescue Timeout::Error
            Process.kill 9, pid
            # collect status so it doesn't stick around as zombie process
            Process.wait pid
        end
        puts "#{server} child exited, pid = #{pid}"
    end
    

    【讨论】:

      【解决方案2】:

      subexec一个机会。来自自述文件:

      Subexec 是一个简单的库,它生成带有可选超时参数的外部命令。它依赖于 Ruby 1.9 的 Process.spawn 方法。此外,它适用于同步和异步代码。

      对于作为 CLI 的 Ruby 包装器的库很有用。例如,使用 ImageMagick 的 mogrify 命令调整图像大小有时会停止并且永远不会将控制权返回给原始进程。输入子执行程序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 2011-07-05
        • 1970-01-01
        • 2010-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多