如果超过5秒,如何退出使用Ruby的进程?

时间:2022-11-30 03:58:12

I'm implementing a checking system in Ruby. It runs executables with different tests. If the solution is not correct, it can take forever for it to finish with certain hard tests. That's why I want to limit the execution time to 5 seconds.

我正在用Ruby实现一个检查系统。它使用不同的测试运行可执行文件。如果解决方案不正确,可能需要永远完成某些硬测试。这就是我想将执行时间限制为5秒的原因。

I'm using system() function to run executables:

我正在使用system()函数来运行可执行文件:

system("./solution");

.NET has a great WaitForExit() method, what about Ruby?.

.NET有一个很棒的WaitForExit()方法,Ruby呢?

Is there a way to limit external process' execution time to 5 seconds?

有没有办法将外部进程的执行时间限制为5秒?

Thanks

2 个解决方案

#1


11  

You can use the standard timeout library, like so:

您可以使用标准超时库,如下所示:

require 'timeout'
Timeout::timeout(5) { system("./solution") }

This way you wont have to worry about synchronization errors.

这样您就不必担心同步错误。

#2


4  

Fork your child which executes "./solution", sleep, check if its done, if not kill it. This should get you started.

叉你的孩子执行“./solution”,睡觉,检查它是否完成,如果没有杀死它。这应该让你开始。

pid = Process.fork{ system("./solution")}
sleep(5)
Process.kill("HUP", pid)

http://www.ruby-doc.org/core/classes/Process.html#M003153

#1


11  

You can use the standard timeout library, like so:

您可以使用标准超时库,如下所示:

require 'timeout'
Timeout::timeout(5) { system("./solution") }

This way you wont have to worry about synchronization errors.

这样您就不必担心同步错误。

#2


4  

Fork your child which executes "./solution", sleep, check if its done, if not kill it. This should get you started.

叉你的孩子执行“./solution”,睡觉,检查它是否完成,如果没有杀死它。这应该让你开始。

pid = Process.fork{ system("./solution")}
sleep(5)
Process.kill("HUP", pid)

http://www.ruby-doc.org/core/classes/Process.html#M003153