gpt4 book ai didi

ruby - 如何在 Ruby 中使子进程超时

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:07 26 4
gpt4 key购买 nike

我想测试一个进程是否正常运行,所以我运行:

cmd = "my unix command"
results = `#{cmd}`

如何为命令添加超时,以便在超过 x 秒时我可以假定它不工作?

最佳答案

Ruby 附带 Timeout module .

require 'timeout'
res = ""
status = Timeout::timeout(5) {res = `#{cmd}`} rescue Timeout::Error

# a bit of experimenting:

res = nil
status = Timeout::timeout(1) {res = `sleep 2`} rescue Timeout::Error
p res # nil
p status # Timeout::Error

res = nil
status = Timeout::timeout(3) {res = `sleep 2`} rescue Timeout::Error
p res # ""
p status # ""

关于ruby - 如何在 Ruby 中使子进程超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10903160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com