如何在ps -p中将时间格式更改为秒?

我写了一个rsync脚本,它也检查脚本进程运行了多长时间。

这是相关部分:

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 

有时候这个过程会卡住,并且运行超过5秒(甚至几天),所以脚本的上面部分应该写入日志。

运行时:

ps -p PID -o etime=

它返回进程已经运行了多长时间。 例:

43:36

但是如果这个过程已经运行了一天以上,那么输出如下所示:

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

我的问题是如何在几秒钟内得到这个数字? 因为我需要确保进程没有运行超过5秒钟。

你可以尝试像这样:

 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 

新版本有etimes选项,可以在几秒钟内返回时间。

这将在Ubuntu上提供输出。 它不适用于RedHat。

ps -p PID -o etimes=