Waiting for Ruby child pid to exit

不羁的心 提交于 2019-12-21 04:29:10

问题


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

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."

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.


回答1:


Use the Timeout module: (code from 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:


Give a chance to subexec. From the README:

Subexec is a simple library that spawns an external command with an optional timeout parameter. It relies on Ruby 1.9's Process.spawn method. Also, it works with synchronous and asynchronous code.

Useful for libraries that are Ruby wrappers for CLI's. For example, resizing images with ImageMagick's mogrify command sometimes stalls and never returns control back to the original process. Enter Subexec.



来源:https://stackoverflow.com/questions/12572500/waiting-for-ruby-child-pid-to-exit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!