Skip to content

Instantly share code, notes, and snippets.

@hirose31
Last active June 7, 2021 07:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirose31/1668178 to your computer and use it in GitHub Desktop.
Save hirose31/1668178 to your computer and use it in GitHub Desktop.
/proc/PID/statからプロセスの起動時刻を知る
use POSIX qw(strftime sysconf _SC_CLK_TCK);
use File::Slurp;
use Time::Piece;
use Time::HiRes qw(time);
my $TIME_OF_BOOT = time_of_boot();
my $CLOCK_TICK = sysconf(_SC_CLK_TCK);
MAIN: {
my $pid = shift or die "missing PID";
my $stat = read_file("/proc/$pid/stat");
my @stats = split /\s+/, $stat;
my $start_unix_time = convert_into_start_unix_time($stats[21]);
printf("%s: since %s (%d)\n",
$pid,
localtime($start_unix_time)->datetime,
$start_unix_time,
);
}
sub time_of_boot {
open my $u, '<', '/proc/uptime' or die $!;
my $buf = <$u>;
my($seconds_since_boot) = (split /\s+/, $buf);
close $u;
return time() - $seconds_since_boot;
}
sub convert_into_start_unix_time {
my $start_time_jiffies = shift;
return int( $TIME_OF_BOOT + ($start_time_jiffies / $CLOCK_TICK) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment