On Wed, 15 Jun 2005, Garance A Drosehn wrote:

> Let's say I have a ruby script which calls system() to run some
> arbitrary program.  Since that program might spiral off into some evil
> infinite-loop, is there some way for me to say "execute this, but for
> no longer than 2 seconds of CPU time"?  In the C-world I might use
> something like setrlimit, but I'm not sure how easy that would be to
> do from within a ruby script.
>
> Note that I don't want to limit the CPU time of the script itself.  I
> just want to limit the CPU time for specific applications that I
> execute via system().

maybe something like

   harp:~ > cat a.rb
   require 'timeout'
   def spawn cmd, sec
     pid = fork{ system cmd }
     begin
       Timeout::timeout(sec){ Process::waitpid2(pid).last }
     rescue Timeout::Error => e
       Process::kill 'TERM', pid rescue nil
       Process::kill 'KILL', pid rescue nil
       Process::waitpid2(pid).last
     end
   end

   p(spawn('sleep 2', 4))

   p(spawn('sleep 4', 2))


   harp:~ > ruby a.rb
   #<Process::Status: pid=6872,exited(0)>
   #<Process::Status: pid=6874,signaled(SIGTERM=15)>

hth.

-a
-- 
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| My religion is very simple.  My religion is kindness.
| --Tenzin Gyatso
===============================================================================