From: anselm Date: 2007-04-16T19:20:07+09:00 Subject: Re: executing a system command and stopping it after a specified duration? On Apr 15, 5:57 am, Robert La Ferla wrote: > I'd like to run a system command and then stop it after specified > amount of time (in seconds or milliseconds.) What's the best way to > do it? I have this handy function ; it raises an exception on timeout/non zero exit status, returns the result of the call otherwise (ie. what the process output on $stdout). In case of timeout it also attemts to kill the process (runs on Unix - no clue about other platforms!) : # # Usage example : # files = run('find -mtime -7') # # Function : # def run(s, maxt = 10*60) begin pipe = IO.popen(s, 'r') rescue Exception => e $stderr << 'Execution of '+s+' has failed :' + e.to_s raise "run failed" end begin Timeout::timeout(maxt) do |t| a = Process.waitpid2(pipe.pid) if a[1].exitstatus != 0 $stderr << 'Error while executing ' + s raise "run failed" end end rescue Timeout::Error => e $stderr << 'Execution of '+s+' has timed out. Killing subprocess' begin Process.kill('KILL', pipe.pid) pipe.close rescue Object => e $stderr << 'Failed killing process : ' + e.to_s end raise "run failed" end out = pipe.gets(nil) pipe.close out end I've edited it a bit to remove some of my specific dependencies - so there might be typos here :) It could be improved to also return the content of $stderr in case of non-zero exit status. Anselm