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

I am implementing a validation system in Ruby. It runs executable files with various tests. If the solution is not correct, it may require endless completion with certain stringent tests. So I want to limit the runtime to 5 seconds.

I use the system () function to run executable files:

system("./solution"); 

.NET has an excellent WaitForExit() method, what about Ruby ?.

Is there a way to limit the runtime of an external process to 5 seconds?

thanks

+6
ruby process execution-time
source share
2 answers

You can use the standard timeout library, for example:

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

This way you don’t have to worry about synchronization errors.

+11
source share

Insert your child who performs "./solution", sleep, check if this is done, if not kill. That 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

+4
source share

All Articles