Waiting for Ruby child pid to exit

前端 未结 2 550
小蘑菇
小蘑菇 2021-02-15 11:31

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:

ser         


        
相关标签:
2条回答
  • 2021-02-15 11:55

    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
    
    0 讨论(0)
  • 2021-02-15 11:57

    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.

    0 讨论(0)
提交回复
热议问题