等待Ruby子pid退出 [英] Waiting for Ruby child pid to exit

查看:65
本文介绍了等待Ruby子pid退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图派生一个子进程,等待它完成,如果在一定时间内没有完成,请杀死它.

I'm trying to fork a sub-process, wait for it to finish, if it doesn't finish within a certain amount of time, kill it.

这是我到目前为止所拥有的:

This is what I have so far:

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秒,如果该进程仍然存在,我想杀死它并将输出标记为"ERROR".

Somewhere after/around Process.wait, I would like some sort of utility to wait 20 seconds, and if the process is still out there, I'd like to kill it and mark output as "ERROR."

我是fork/exec的新手.我的代码实际上是可以派生的,但是我只是不知道如何处理它的等待/杀死方面.

I'm new to fork/exec. My code actually forking works, but I just don't know how to approach the waiting / killing aspect of it.

推荐答案

使用 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

这篇关于等待Ruby子pid退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆