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

发布于 2024-10-10 02:29:32 字数 282 浏览 0 评论 0原文

我正在用 Ruby 实现一个检查系统。它运行具有不同测试的可执行文件。如果解决方案不正确,则可能需要很长时间才能完成某些困难的测试。这就是为什么我想将执行时间限制为 5 秒。

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

system("./solution");

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

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

谢谢

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.

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

system("./solution");

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

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

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

他是夢罘是命 2024-10-17 02:29:32

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

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

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

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.

美人骨 2024-10-17 02:29:32

分叉执行“./solution”的孩子,睡眠,检查它是否完成,如果没有则杀死它。这应该可以帮助您开始。

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

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文