3

I wrote a rsync script which also checks for how long the process of the script has been running.

This is the relevant part:

time=$(ps -p $processid -o etime= | awk -F: '{print $2}') # number of seconds the process is running.

if [ $(ps -ef | grep $(basename $0) &>/dev/null && echo $?) -eq "0" ] && [ "$time" -gt "5" ]; then # Check if there's a running process with the script name which is running for more than 5 seconds.
        echo "$message"
        print_log $message
        print_log "--------- END --------"
        exit 1
fi

Sometimes the process gets stuck and runs for more than 5 seconds (and even days) so the above part of the script is supposed to write it to the log.

When running:

ps -p PID -o etime=

It returns how long the process has been running. Example:

43:36

But if the process has been running for more than a day, then the output looks like so:

[root@do01 ~]# ps -p 28518 -o etime=
 7-22:43:36

My question is how can I get this number in seconds? because I need to make sure the process has not been running for more than 5 seconds.

Itai Ganot
  • 10,424
  • 27
  • 88
  • 143

3 Answers3

2

You can try something like:

time=$(ps -p $processid -o etime= | tr -d ' ');
time_in_seconds=$(case ${#time} in "8") echo ${time: -2}+${time: -5:2}*60+${time: -8:2}*3600 | bc;;  "5")  echo ${time: -2}+${time: -5:2}*60 | bc;; *) echo $(echo $time | cut -d'-' -f1)*86400+${time: -2}+${time: -5:2}*60+${time: -8:2}*3600 | bc;; esac)
echo $time_in_seconds

Newer versions have etimes option which returns time in seconds.

Laurentiu Roescu
  • 2,246
  • 16
  • 17
2

This will give output in seconds on Ubuntu. It does not work on RedHat.

ps -p PID -o etimes=

piotrektt
  • 184
  • 2
  • 14
0

Here is a couple different solutions for platforms not supporting etimes=. First maybe Linux systems only

etime=$(date -d "$(stat -c %y /proc/${pid} | cut -d ' ' -f 1,2)" +%s); \
  echo "$(date +%s) - ${etime}" | bc -l

Second is pretty nice awk option:

ps -o etime= -p "${pid}" | \
  tr -d ' ' | tr '-' ':' | \
  awk -F':' '{ secs=0; split("86400 3600 60 1", t_factor, " "); tf=4; for(i=NF;i>0;i--){secs+=$i*t_factor[tf]; tf--};print secs }'
JGurtz
  • 523
  • 5
  • 13