Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a process run with Ruby if it takes more than 5 seconds?

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

like image 589
Alex Avatar asked Jan 01 '11 12:01

Alex


2 Answers

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.

like image 166
Timon Vonk Avatar answered Sep 20 '22 08:09

Timon Vonk


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

like image 23
EnabrenTane Avatar answered Sep 22 '22 08:09

EnabrenTane