Có lẽ điều này sẽ giúp người khác tìm cách đạt được chức năng thời gian chờ tương tự nhưng cần thu thập đầu ra từ lệnh shell.
Tôi đã điều chỉnh phương thức @ shurikk để làm việc với Ruby 2.0 và một số mã từ Fork child process with timeout and capture output để thu thập kết quả.
def exec_with_timeout(cmd, timeout)
begin
# stdout, stderr pipes
rout, wout = IO.pipe
rerr, werr = IO.pipe
stdout, stderr = nil
pid = Process.spawn(cmd, pgroup: true, :out => wout, :err => werr)
Timeout.timeout(timeout) do
Process.waitpid(pid)
# close write ends so we can read from them
wout.close
werr.close
stdout = rout.readlines.join
stderr = rerr.readlines.join
end
rescue Timeout::Error
Process.kill(-9, pid)
Process.detach(pid)
ensure
wout.close unless wout.closed?
werr.close unless werr.closed?
# dispose the read ends of the pipes
rout.close
rerr.close
end
stdout
end
Điều đó không đúng. Sub-shell đang chạy lệnh sẽ kết thúc khi quá trình ruby cha kết thúc. Vui lòng đưa ra một ví dụ cụ thể hơn. –
@BenLee: Quy trình gốc không chấm dứt khi hết thời gian chờ. –
@ MladenJablanović, trong một thử nghiệm nhanh chóng. Tôi tạo ra một tập tin ruby mà không làm gì ngoài: 'require 'timeout'; Hết giờ :: thời gian chờ (100) {'ngủ 500'}'. Trong khi chạy nó, tôi làm 'ps aux | grep ngủ' và xem quá trình ngủ. Sau đó, tôi gửi SIGKILL cho quá trình ruby và chạy lại lần nữa 'ps aux | grep ngủ' và không còn nhìn thấy quá trình con. –