When was a process started
Solution 1
On Linux at least, you can also do:
ps -o lstart= -p the-pid
to have a more useful start time.
Note however that it's the time the process was started, not necessarily the time the command that it is currently executing was invoked. Processes can (and generally do) run more than one command in their lifetime. And commands sometimes spawn other processes.
The mtimes of the files in /proc
on Linux (at least) are generally the date when those files were instantiated, which would be the first time something tried to access them or list the directory content.
For instance:
$ sh -c 'date +%T.%N; sleep 3; echo /proc/"$$"/xx*; sleep 3; stat -c %y "/proc/$$/cmdline"'
13:39:14.791809617
/proc/31407/xx*
2013-01-22 13:39:17.790278538 +0000
Expanding /proc/$$/xx*
caused the shell to read the content of /proc/$$
which caused the cmdline
file to be instantiated.
See also: Timestamp of socket in /proc//fd
Solution 2
proc is a virtual file system so I wouldn't rely on any file status information.
The start time of the process is located at /proc/PID/stat column 22. It is given in jiffies after system boot. To convert it to seconds you have to divide it by sysconf(_SC_CLK_TCK)
which is 100 for most systems (but not all!).
To get the time of system boot you determine the current uptime in seconds which is the first value of /proc/uptime.
Having those two numbers you subtract the first from the second and you get the number of seconds passed since starting the program.
Example (for pidgin):
PID=$(pidof pidgin)
STARTTIME=$(awk '{print int($22 / 100)}' /proc/$PID/stat)
UPTIME=$(awk '{print int($1)}' /proc/uptime)
NOW=$(date +%s)
DIFF=$((NOW - (UPTIME - STARTTIME)))
date -d @$DIFF
Note: this simple example doesn't work if pidof
returns multipe PIDs.
Related videos on Youtube
Jerry
Updated on September 18, 2022Comments
-
Jerry almost 2 years
To know when was a process started, my first guess was to check the time when
/proc/<pid>/cmdline
was written/modified the last time.ps
also shows aSTART
field. I thought both of these sources would be the same. Sometimes they are not the same. How could that be? -
Jerry over 11 yearsAny idea about when does proc/<pid>/cmdline gets written to? well any of proc/<pid> entries for that matter.
-
hayath786 over 11 yearsUsually those files are generated by the kernel dynamically whenever you try to read them and most of them also have a dynamical content. cmdline doesn't but I can't imagine that there is an official policy stating that is has to be created once on process startup and never be touched again.
-
oแดษนวษฅษ almost 6 yearsYou can get _SC_CLK_TCK value from command line by executing "getconf CLK_TCK"