Tom Womack
Tom Womack

Reputation: 791

How to determine the date-and-time that a Linux process was started?

If I look at /proc/6945/stat then I get a series of numbers, one of which is the number of CPU-centiseconds for which the process has been running.

But I'm running these processes on heavily-loaded boxes, and what I'm interested in is the clock-time when the job will finish, for which I want to know the clock-time that it started.

The timestamps on files in /proc/6945 look to be in the right sort of range but I can't find a particular file which consistently has the right clock-time on it.

As always I can't modify the process.

Upvotes: 3

Views: 3056

Answers (4)

adrianlzt
adrianlzt

Reputation: 2031

Bash command to get the start date of some process:

date -d @$(cat /proc/PID/stat | awk "{printf \"%.0f\", $(grep btime /proc/stat | cut -d ' ' -f 2)+\$22/$(getconf CLK_TCK);}")

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249642

Use the creation timestamp of the /proc/6945 directory (or whatever PID), rather than looking at the files it contains. For example:

ls -ld /proc/6945

Upvotes: 0

Corey Henderson
Corey Henderson

Reputation: 7465

I have a project on github that does this in perl. You can find it here:

https://github.com/cormander/psj

The code you're wanting is in lib/Proc/PID.pm, and here is the snippit (with comments removed):

use POSIX qw(ceil sysconf _SC_CLK_TCK);

sub _start_time {
    my $pid = shift->pid;

    my $tickspersec = sysconf(_SC_CLK_TCK);

    my ($secs_since_boot) = split /\./, file_read("/proc/uptime");
    $secs_since_boot *= $tickspersec;

    my $start_time = (split / /, file_read("/proc/$pid/stat"))[21];

    return ceil(time() - (($secs_since_boot - $start_time) / $tickspersec));
}

Beware the non-standard code function file_read in here, but that should be pretty straight forward.

Upvotes: 1

Tom Womack
Tom Womack

Reputation: 791

Timestamps of the directories in /proc are useless.

I was advised to look at 'man proc'; this says that /proc/$PID/stat field 21 records the start-time of the process in kernel jiffies since boot ... so:

open A,"< /proc/stat"; while (<A>) { if (/^btime ([0-9]*)/) { $btime = $1 } }

to obtain the boot time, then

my @statl = split " ",`cat /proc/$i/stat`;
$starttime_jiffies = $statl[21];
$starttime_ut = $btime + $starttime_jiffies / $jiffies_per_second;
$cputime = time-$starttime_ut

but I set $jiffies_per_second to 100 because I don't know how to ask the kernel for its value from perl.

Upvotes: 2

Related Questions