手机
当前位置:查字典教程网 >脚本专栏 >linuxshell >Shell脚本获取进程的运行时间
Shell脚本获取进程的运行时间
摘要:在我们的系统中,我曾写了一个脚本去定时更新一些repository,但偶尔会遇到问题,比如:gitpull之时可能会卡在那里(可能由于某时刻...

在我们的系统中,我曾写了一个脚本去定时更新一些repository,但偶尔会遇到问题,比如:git pull之时可能会卡在那里(可能由于某时刻的网络问题),它会阻碍后面的下一次更新。

所以我就在想,我今后启动这个脚本时,进行检查,如果上次运行的脚本还没结束,而且过了某个时间阀值,就把它及其子进程给kill掉。然后,我就需要写了一个可以查询某个进程已经运行了多少时间(以second为单位)的脚本。

注意:这并不是是指进程消耗的CPU时间,这里是当前时间减去进程启动时的时间,是这个时间段。

本来,ps本身也提供了选项来查询的,但是比较直观和形象(如 10:32这样的),不是用seconds为单位,并不方便在脚本中直接使用。ps中的关于进程时间的命令如下:

复制代码 代码如下:

[root@jay-linux jay]# ps -p 4260 -o pid,start_time,etime,comm

PID START ELAPSED COMMAND

4260 Apr18 16-08:57:25 gnome-session

其中第三列的16-08:57:25就是进程运行的时间,为:16天8小时57分25秒。

我自己根据一些/proc文件系统中的信息,查询进程运行时间脚本分享如下:

复制代码 代码如下:

#!/bin/bash

function show_elapsed_time()

{

user_hz=$(getconf CLK_TCK) #mostly it's 100 on x86/x86_64

pid=$1

jiffies=$(cat /proc/$pid/stat | cut -d" " -f22)

sys_uptime=$(cat /proc/uptime | cut -d" " -f1)

last_time=$(( ${sys_uptime%.*} - $jiffies/$user_hz ))

echo "the process $pid lasts for $last_time seconds."

}

if [ $# -ge 1 ];then

for pid in $@

do

show_elapsed_time $pid

done

fi

while read pid

do

show_elapsed_time $pid

done

执行过程和结果如下:

复制代码 代码如下:

[root@jay-linux jay]# ./get_process_time.sh 4260

the process #4260 lasts for 1415417 seconds.

后续我再写两篇简单讲讲/proc/stat, /proc/$pid/stat, /proc/uptime吧。

【Shell脚本获取进程的运行时间】相关文章:

Shell脚本定时备份清除运行系统日志的代码

Linux shell脚本编程if语句的使用方法(条件判断)

Linux Shell脚本编程的注意事项

Shell脚本test命令使用总结和实例

shell grep 查找进程的小技巧

shell实现四则运算简单方法

在Shell命令行处理JSON数据的方法

Shell脚本自动更新hosts实现免翻墙访问google

bash获取当前路径示例

Shell脚本编程中常用的数学运算实例

精品推荐
分类导航