Friday, September 18, 2009

Find process running time in UNIX


Question. How to find out how long a process is running in an UNIX system ?

Ans: Here are some tips to find the process' running time in an UNIX system.

----------------
For 2.6 kernels:
----------------

Identify your process Id

and then do a

ls -ld /proc/PID-OF-YOUR-PROCESS

So the modification time listed on the above file(directory) is the time that the process has started.

e.g. I have started a process say "sleep 10000" few minutes back

$ ps -ef | grep "[s]leep 10000"
jsaikia 24375 23306 0 22:13 pts/10 00:00:00 sleep 10000

$ ls -ld /proc/24375
dr-xr-xr-x 6 jsaikia staff 0 2009-09-18 22:14 /proc/24375

So, "2009-09-18 22:14" is the start time of the above sleep process; if I subtract this time from the current time I can find how long this process has been running.

For subtraction you can have a script like this:

#!/bin/sh

T1=$(date +%s -d "$1")
T2=$(date +%s -d "$2")
((diffsec=T1-T2))
echo - \
| awk -v D=$diffsec '{printf "%d:%d:%d\n",D/(60*60),D%(60*60)/60,D%60}'

So that you can execute like this:

$ sh cal-tdiff.sh "$(date)" "2009-09-18 22:14"
0:22:56

----------------
For 2.4 kernels:
----------------
For 2.4 kernels, the modification time on the "/proc/PID-OF-YOUR-PROCESS" will be the current system time (unlike 2.6 kernels where its the actual process start time)

So how to find the running time of a process on a 2.4 kernel UNIX system ?

Here is the way (this is going to work for 2.6 also)

e.g.

$ ps -ef | grep [s]leep
root 7702 7689 0 17:34 pts/0 00:00:00 sleep 100000

so 7702 is the pid of the above process.

$ pd=7702
$ expr $(awk '{print $1}' FS=\. /proc/uptime) - $(awk '{printf ("%10d\n",$22/100)}' /proc/$pd/stat)

The output will show the number of seconds the process(with pid=pd) is running.

2 comments:

herbert said...

i guess on most ps versions you can also directly use the options -eo etime:

herbert@herbert:~$ ps -eo pid,etime,args | grep X11
3281 08:32:10 /usr/X11R6/bin/X

Jadu Saikia said...

@herbert, thanks a lot. This is useful.

© Jadu Saikia www.UNIXCL.com