SoFunction
Updated on 2025-03-09

Shell script gets the running time of the process

In our system, I once wrote a script to update some repository regularly, but occasionally I encountered problems, such as: git pull might get stuck there (maybe due to network problems at some point), which would hinder the next update later.
So I was thinking, when I start this script in the future, I check it. If the script I ran last time has not ended and has passed a certain time threshold, I will kill it and its child processes. Then I need to write a script that can query how much time a process has been running (in second).
Note: This does not refer to the CPU time consumed by the process. Here is the current time minus the time when the process starts, which is this time period.

Originally, ps itself also provides options for querying, but it is more intuitive and vivid (such as 10:32). It is not used as seconds and is not convenient to use directly in scripts. The commands about process time in ps are as follows:

Copy the codeThe code is as follows:

[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

Among them, 16-08:57:25 in the third column is the time when the process runs, which is: 16 days, 8 hours, 57 minutes and 25 seconds.

Based on some information in the /proc file system, I share the following script for querying the process runtime:

Copy the codeThe code is as follows:

#!/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

The execution process and results are as follows:
Copy the codeThe code is as follows:

[root@jay-linux jay]# ./get_process_time.sh 4260
the process #4260 lasts for 1415417 seconds.

I will write two more articles to briefly talk about /proc/stat, /proc/$pid/stat, /proc/uptime.