Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 a START field. I thought both of these sources would be the same. Sometimes they are not the same. How could that be?

share|improve this question

2 Answers 2

up vote 15 down vote accepted

On Linux at least, you can also do:

ps -o lstart= -p the-pid

to have a more useful start time. 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/<pid>/fd

share|improve this answer

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.

share|improve this answer
    
Any idea about when does proc/<pid>/cmdline gets written to? well any of proc/<pid> entries for that matter. –  swair Jan 22 '13 at 13:30
1  
Usually 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. –  scai Jan 22 '13 at 13:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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