At times, you may want to determine the elapsed wall-clock time or uptime for a running process. While you can determine the process’ elapsed time using certain versions of the ps utility, it can also be determined using a simple shell script with a bit of perl. Both these methods are described below with the init process (PID = 1):

SOLUTION 1: The ps utility on some variants of UNIX (e.g. Linux, but not Solaris)

ps -oetime 1
    ELAPSED
      39:45

 

SOLUTION 2: A shell script with a bit of perl (should work on all variants of UNIX)

Download the shell script (puptime.ksh) or copy and paste from below:

#!/bin/ksh
# puptime.ksh - Gavin Satur - http://cybergav.in/2009/11/09/puptime
# Simple script to calculate the uptime (elapsed wall clock time) of a process
##############################################################################
#
# Accept PID and do some basic validation
#
proc_pid=$1
if [ -z "$proc_pid" ]; then
   print "\nERROR : Missing input argument. SYNTAX: ksh puptime.ksh \n"
   exit 999
fi
if [ ! -d /proc/$proc_pid ]; then
   print "\nERROR : No directory for PID $proc_pid in /proc. Check if process is running!\n"
   exit 999
fi
#
# Calculate start time of process and current time in epoch time using a bit of perl
#
proc_stime=`perl -e 'use File::stat;  my $filename = "$ARGV[0]"; $sb = stat($filename); printf "%s", $sb->mtime;' /proc/$proc_pid`
currtime=`perl -e 'print time;'`
#
# Calculate process uptime in seconds and then slice'n'dice for human-friendly output
#
proc_time=$(( currtime - proc_stime ))
proc_time_days=$(( proc_time / 86400 ))
proc_time_secs=$(( proc_time % 86400 ))
proc_time_hours=$(( proc_time_secs / 3600 ))
proc_time_secs=$(( proc_time_secs % 3600 ))
proc_time_minutes=$((proc_time_secs / 60 ))
proc_time_secs=$(( proc_time_secs % 60 ))
print "\nUPTIME FOR PROCESS WITH PID $proc_pid = $proc_time_days day(s) $proc_time_hours hour(s) $proc_time_minutes minute(s) $proc_time_secs second(s) \n"
./puptime.ksh 1
UPTIME FOR PROCESS WITH PID 1 = 0 day(s) 0 hour(s) 39 minute(s) 37 second(s)
VN:F [1.9.22_1171]
Rating: +2 (from 2 votes)

Tagged with:

Filed under: Linux

Like this post? Subscribe to my RSS feed and get loads more!