Waiting for a Ruby Baby Pid

I try to unlock the subprocess, waiting for it to complete, if it does not end in a certain 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 utility to wait 20 seconds, and if the process is still there, I would kill it and mark the output as "ERROR".

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

+5
source share
2 answers

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 
+9
source

Give the opportunity to subexec . From README:

Subexec is a simple library that spawns an external command with an optional timeout parameter. It uses the Ruby 1.9 Process.spawn method. In addition, it works with synchronous and asynchronous code.

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

0
source

Source: https://habr.com/ru/post/952331/


All Articles