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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0