For a process management,I would need to remove a process that exceeds a certain amount of CPU time, for example 1 hour.In PS command ,it has TIME parameter shows the total CPU time of a process .So is this the correct way to take the CPU time of a process? Also is there any other commands that could be used in calculating CPU time of process.

  • you probably need to use ps or top with the right option added to cut and then to kill -9 but I think nobody will provide you such a script without you showing a bit of your work. – Kiwy Nov 28 '13 at 9:35
  • If you already know what process is exceeding, you could use sar -X to monitor that specific PID. – ludiegu Nov 30 '13 at 10:53

On most systems, you can use the ulimit command when you start the program to limit the amount of CPU time it can use. Under the hood, this calls setrlimit with the argument RLIMIT_CPU. After the program has used that much time, the program is killed.

(ulimit -t 3600; myprogram)

You can refine further by setting a soft limit after which the program receives the SIGXCPU signal (which it can catch) and a hard limit after which the program receives the SIGKILL signal (which is unavoidably fatal).

(ulimit -t -S 3590; ulimit -t -H 3600; myprogram)

I don't know of any shell utility to change the limit of a running program. You can cause the process to execute the setrlimit system call via ptrace, for example using a debugger. Note that some security frameworks disable this use of ptrace (e.g. it's disabled by default on current Ubuntu releases), I don't know whether RHEL 5 allows it.

gdb -n -pid 1234 -batch -x /dev/stdin <<EOF
call setrlimit(RLIMIT_CPU, {(rlim_t) 3590, (rlim_t) 3600})

(1234 is the process ID, and the two numbers inside the braces are the soft and hard limit.)


Depending on the precision you need, invoking ps and some friends may be sufficient.

However, keep in mind that ps gets its data from somewhere; there's nothing magical about that particular application.

Have a look at /proc/$$/sched and specifically the value for se.sum_exec_runtime. That value is the total number of nanoseconds the process has spent on the CPU. I'm not going to spend a lot of time to trace its history, but it looks like the value has been kept track of at least since 2.6.32.

To get a more useful value (milliseconds), take the reported value and divide it by 1,000,000.

There are probably other ways to get the same data, but it might be non-trivial without resorting to syscalls into the kernel, which is not an easy thing to do from a shell script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.