How long has that command been running? (in seconds)

The ps command is fairly obtuse at the best of the times, but I am very thankful for things like ps -eo uid,command. I wish it were as easy to have ps report the starttime of a process in a form I can use. See my pain looking at the start-time and elapsed time (which is not wall-clock) for a rather antiquarian system.

# ps -eo stime,etime
... selected extracts ...
Apr20  1-02:30:30
 2013 731-03:01:37
12:59    01:42:25
14:41       00:00

Yeah, I really don't want to touch that with any scripting tool. Best to head to /proc/... you may actually want to use ps or something like pgrep to determine the PID of the progress of interest.

According to proc(5), we want the 28th element in /proc/PID/stat:  "starttime: ...The time in jiffies the process started after system boot.". A jiffie is explained in time(7) -- this from RHEL 5:

   The Software Clock, HZ, and Jiffies
       The  accuracy  of  many system calls and timestamps is limited by the resolution of
       the software clock, a clock  maintained  by  the  kernel  which  measures  time  in
       jiffies.  The size of a jiffy is determined by the value of the kernel constant HZ.
       The value of HZ varies across kernel versions and hardware platforms.  On  x86  the
       situation is as follows: on kernels up to and including 2.4.x, HZ was 100, giving a
       jiffy value of 0.01 seconds; starting with 2.6.0, HZ was raised to 1000,  giving  a
       jiffy of 0.001 seconds; since kernel 2.6.13, the HZ value is a kernel configuration
       parameter and can be 100, 250 (the default) or 1000, yielding a jiffies  value  of,
       respectively, 0.01, 0.004, or 0.001 seconds.

But remember that that is jiffies past system boot, so we would have to determine boot-time, which is available via /proc/uptime.... but if we're looking for epoch time, we need to take current time - uptime (gives us epoch time at boot) + start_time of process in seconds.... ridiculous!

Here's a sample of how to get the start time of a process given a PID (here I'm just using $$ as the PID to test). Hope it saves you some pain:

# date --date=@$(< /proc/$$/stat tr ' ' '\n' | awk -vuptime=$(awk '{print $1}' /proc/uptime) 'NR == 27 {print int(systime() - uptime + ($1 / 1000))}')
Sat Apr 20 13:01:20 NZST 2013



Comments

Popular posts from this blog

ORA-12170: TNS:Connect timeout — resolved

Getting MySQL server to run with SSL

From DNS Packet Capture to analysis in Kibana