16

We have a script which runs on our web servers, triggered by customer action, which initiates a unix process to generate some cache files. Because this process acts upon files supplied by our customer, it sometimes misbehaves, running so long that the PHP process which spawns it times out or using so much CPU time that a sysadmin will kill it.

Is there any command which I could run which would limit the CPU time / runtime of the process? I am looking for a command like /usr/bin/time, where I could run that command and pass it the commandline I want it to run and limit.

0

3 Answers 3

13

In addition to Gilles answer there is cpulimit tool that does exactly what you want - including modifing in runtime. Additionally it can limit to only certain CPUs/Cores IIRC.

12

From within a program, call setrlimit(RLIMIT_CPU, ...). From the shell, call ulimit -t 42 (this is not standard but supported by most shells (including bash and ksh) on most unix variants). This causes the current process to be killed once it has used up N seconds of CPU time. The limitation is inherited by child processes. A common shell idiom is (ulimit -t 42; runaway_process) if you want to be able to run other unlimited processes afterwards from the same shell.

See also Is there a way to limit the amount of memory a particular process can use in Unix? . The principle is the same, you're just limiting a different resource.

4
  • The problem is, I don't have the source code for the program so I can't add setrlimit and I'm spawning it through PHP so I don't have a shell...
    – Josh
    Commented Dec 8, 2010 at 23:31
  • 6
    @Josh: If you're looking for a construct analogous to time php /cgi/foo.php, you can use bash -c 'ulimit -t 42; exec "$0" "$@"' php /cgi/foo.php. Commented Dec 8, 2010 at 23:40
  • @Josh apache? also I think this stuff can be set system wide... Commented Dec 9, 2010 at 13:10
  • @xenoterracide yes it's Apache, but I only want to limit this one process, not all apache processes. Gilles' bash oneliner may work great!
    – Josh
    Commented Dec 9, 2010 at 14:59
3

You can also use the timeout command to block a process from running for longer than a specified amount of time.

example

$ date
Mon May  6 07:35:07 EDT 2013
$ timeout 5 sleep 100
$ date
Mon May  6 07:35:14 EDT 2013

See the timeout man page for further details.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .