How to get a process uptime under different OS?

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#*:}))

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.


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.

Tags:

Process

Uptime