Under Linux I can get a process’s uptime in seconds with:
echo $(($(cut -d "." -f1 /proc/uptime) - $(($(cut -d " " -f22 /proc/$PID/stat)/100))))
But how can I get it under different OS? ex.: SunOS, HP-UX, AIX?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
On any POSIX-compliant system, you can use the etime column of ps.
LC_ALL=POSIX ps -o etime= -p $PID
The output is broken down into days, hours, minutes and seconds with the syntax [[dd-]hh:]mm:ss. You can work it back into a number of seconds with simple arithmetic:
t=$(LC_ALL=POSIX ps -o etime= -p $PID)
d=0 h=0
case $t in *-*) d=$((0 + ${t%%-*})); t=${t#*-};; esac
case $t in *:*:*) h=$((0 + ${t%%:*})); t=${t#*:};; esac
s=$((10#$d*86400 + 10#$h*3600 + 10#${t%%:*}*60 + 10#${t#*:}))
Method 2
echo $(( $(date +'%s') - $(stat -c '%Y' /proc/$PID) ))
This should work in any system with a /proc filesystem. Unfortunately I don’t have the means to test it.
Method 3
I don’t know if there is one command for all systems, but you can use the Unix Rosetta Stone to translate the commands to each system.
Method 4
This will work:
ps -eo etime,cmd | grep process_name
Method 5
Discovered one that works across Linux (probably all versions) and Solaris (at least, 5.9) – no access to other OS’s to test it and too lazy to check docs 🙂
boottime=$(who -b | awk '/ /{print $3 " " $4}')")
is the time the system was booted in yyyy/mm/dd HH:MM:SS format, so converting to epoch-seconds is:
bootepoc=date -d "$boottime" +%s
and time its been up in seconds is obviously just current epoc-time minus that ie. $(( $(date +%s) - $bootepoc ))
If you want that as a more formatted date, might be easier going with another answer although other scripting languages can get you there (probably possible other ways too).
(you didnt say how you wanted it but gave a different example).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0