[ale] Finding the age of a process in seconds. How hard can it be?
Ted W.
ted-lists at xy0.org
Thu May 12 00:31:58 EDT 2016
Today I found myself completely confounded by a simple question. How do
you identify the age of a process in seconds? Let's see if we can't
learn something.
At first, this issue seemed quite simple. Surely `ps` can tell you. But
the answer proved more complicated. It looks like `ps` can /sometimes/
tell you... depending on the version of procps you happen to have
installed. You probably know that the `ps` command has the available
option "etime". This shows you the time in format DD-HH:MM:SS. Handy,
but not very easy to parse. Enter the newer version of `ps` which has
the "etimes" option (notice the addition of the "s" there) which shows
the process age in seconds. You can probably guess which version of
procps is installed on CentOS 6 (hint: There's a reason I'm writing this
email).
So now that `ps` is out, let's dig a little deeper. Surely this
information is available in /proc (newer versions of procps have to get
it from somewhere, right?). Specifically, let's look at
/proc/[pid]/stat. Lots of pretty strings of numbers. A quick look at
`man 5 proc` shows us some possibilities, but these values all seem
relative to other times such as system boot time, related to cputime
used, in an alien unit of measurement called a "jiffy" or possibly
shifted by sysconf(_SC_CLK_TCK). Maybe the man page can tell us if
there's another file we could use in /proc/[pid]. /proc/[pid]/exe looks
interesting. According to the man page, this file is a symbolic link to
the actual executable represented by the PID which . Let's see if stat
can tell us when this file was last modified.
`stat -c %Y /proc/[pid]/exe`
Hey, that looks like the right value of time since we started our
process. Now we just need to subtract this from `date +%s`:
`expr $(date +%s) - $(stat -c %Y /proc/[pid]/exe)`
VOILA!
This is the method I've chosen to use. I'd love to know if there is a
simpler method available on "older" Linux distributions. I'm sure this
is not the easiest route, only the route I've settled for after several
hours of investigation today. The closest alternative I came across was
using a combination of `awk '{print $1}' /proc/uptime` minus `date +%s`
and then adding back in the "starttime" value ($22) from
/proc/[pid]/stat. This, while close, was often less accurate than
subtracting the last modified time of /proc/[pid]/exe from the current
time. It was fairly close, however, leading me to believe it may be due
to rounding errors or errors in some of the unit conversions involved.
Cheers,
Ted
More information about the Ale
mailing list