linux / process uptime / exact
How to get (semi)exact uptime values for processes?
If you look at the ps faux
listing, you’ll see a bunch of values:
walter 27311 0.8 1.8 5904852 621728 ? SLl sep06 61:05 \_ /usr/lib/chromium-browser/...
walter 27314 0.0 0.2 815508 80852 ? S sep06 0:00 | \_ /usr/lib/chromium-brow...
walter 27316 0.0 0.0 815508 14132 ? S sep06 0:01 | | \_ /usr/lib/chromium-...
That second value (27311) is the PID, the tenth (61:05) how much CPU time has been spent. And the ninth (sep06) is when the process started.
You can shorten the listing:
$ ps -p 27311 -o pid,start_time,bsdtime
PID START TIME
27311 sep06 61:05
And you can also get more granularity (and readability) out of the times:
$ ps -p 27311 -o pid,lstart,cputime
PID STARTED TIME
27311 Wed Sep 6 14:48:35 2017 01:01:05
Internally, ps(1)
fetches the data from /proc/[pid]/stat
. Read about
its format in man 5 proc
.
For instance, to fetch the start time, the following shell script would
do the trick, by fetching the 22nd value from /proc/[pid]/stat
. The
process start time is stored as seconds-since-boot value:
$ get_proc_starttime() {
PID=$1
SYSUP=$(cut -d. -f1 /proc/uptime)
PIDUP=$((SYSUP-$(awk 'BEGIN{CLK_TCK=100}{printf "%lu",$22/CLK_TCK}' /proc/$PID/stat)))
date -R -d "-$PIDUP seconds"
}
$ get_proc_starttime 27311
Wed, 06 Sep 2017 14:48:36 +0200
Apropos the time in seconds-since-boot format. That’s also the times
you see in the default dmesg(1)
output:
$ dmesg | head -n1
[ 0.000000] Initializing cgroup subsys cpuset
If you want to make sense of the times (and don’t have a nice
/var/log/kern.log
to look at), you could translate the time-value like
this:
$ SYSUP=$(cut -d. -f1 /proc/uptime); dmesg |
sed -e 's/^\[\([^.]*\)\.[^]]*\]/\1/' |
while read x; do echo "[$(date -R -d "-$((SYSUP-${x%% *})) seconds")] ${x#* }"
done | head -n1
[Tue, 25 Jul 2017 16:04:59 +0200] Initializing cgroup subsys cpuset
But, you won’t need that; dmesg itself also has an appropriate flag as
well: dmesg -T
$ dmesg -T | head -n1
[Tue Jul 25 16:04:58 2017] Initializing cgroup subsys cpuset