0

I am trying to run some computational-intense program from Ruby via the following command:

%x(heavy_program)

However, I sometimes want to limit the running time of the program. So I tried doing

%x(ulimit -St #{max_time} & heavy_program)

But it seems to fail; the "&" trick does not work even when I try it in a running sh shell outside Ruby.

I'm sure there's a better way of doing this...

Gadi A
  • 3,449
  • 8
  • 36
  • 54

1 Answers1

3

use either && or ;:

%x(ulimit -St #{max_time} && heavy_program)

%x(ulimit -St #{max_time}; heavy_program)

However using ulimit may be not what you really need, consider this code:

require 'timeout'
Timeout(max_time){ %x'heavy_program' }

ulimit limits CPU time, and timeout limits total running time, as we, humans, usually count it.

so, for example, if you run sleep 999999 shell command with ulimit -St 5 - it will run not for 5 seconds, but for all 999999 because sleep uses negligible amount of CPU time

zed_0xff
  • 32,417
  • 7
  • 53
  • 72
  • Thanks! Could you elaborate on the difference between "&", "&&" and ";" in this context? – Gadi A Jan 17 '13 at 09:39
  • 2
    `&` means run specified task in background, and it will not likely work from ruby's `%x`; `cmdA && cmdB` means "run cmdB ONLY IF cmdA succeed"; `cmdA; cmdB` means "run cmdA first, then cmdB" – zed_0xff Jan 17 '13 at 09:43