10

In linux, from /proc/PID/stat, I can get the start_time (22:nd) field, which indicates how long after the kernel booted the process was started.

What is a good way to convert that to a seconds-since-the-epoch format? Adding it to the btime of /proc/stat?

Basically, I'm looking for the age of the process, not exactly when it was started. My first approach would be to compare the start_time of the process being investigated with the start_time of the current process (assuming it has not been running for long).

Surely there must be way better ways.

I didn't find any obvious age-related parameters when looking at https://www.kernel.org/doc/Documentation/filesystems/proc.txt

So, What I have currently is:

process age = (current_utime - ([kernel]btime + [process]start_time))

Any alternative ways that are more efficient from within a shell script? (Ideally correct across DST changes)

MattBianco
  • 3,704

2 Answers2

15

Since version 3.3.0, the ps of procps-ng on Linux has a etimes output field that gives you the elapsed time in seconds since the process was started (which by the way is not necessarily the same thing as the elapsed time since the last time that process executed a command (if at all!) (the time that process has been running the command in the process name), so may not be as useful as you thought).

So you can do:

ps -o etimes= -p "$pid"

For the start time as Unix epoch time (with GNU date):

(export TZ=UTC0 LC_ALL=C; date -d "$(ps -o lstart= -p "$pid")" +%s)

Note that you cannot use the modification time of /proc/$pid. That is just the time those files were instantiated which has nothing to do with the start time of the process.

11

age of process : human readable form

ps -p 1234 -o etime -h
        1-02:03:04

second since epoch for a process

stat --format=%Y /proc/1234

Age in second

expr $(date +%s) - $(stat --format=%Y /proc/1234)

additionnal ressources ps(1), stat(1)

Archemar
  • 31,554