5

This question already has an answer here:

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)

marked as duplicate by mattdm, dr01, Ramesh, mdpc, don_crissti Nov 9 '15 at 20:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

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.

  • This is exactly the answer I was looking for. – MattBianco Nov 10 '15 at 10:38
3

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)

  • The first and third do not appear to address the question. – Thomas Dickey Oct 26 '15 at 8:43
  • question is unclear, OP ask both for second-since-epoch and age. (second-since-started) – Archemar Oct 26 '15 at 8:46
  • I got three different results: the first failed, the second worked (1445849311), and the third gave me 16 (apparently not seconds since the epoch). – Thomas Dickey Oct 26 '15 at 8:49
  • second is start time since epoch, third is age in second – Archemar Oct 26 '15 at 8:51
  • using stat on the process' /proc/PID directory was clever! Didn't think of that one myself. Feels a bit hackish, though. – MattBianco Oct 26 '15 at 8:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.