在Linux系统中,查看进程的运行时长可以通过以下几种方法实现:
ps
命令ps -eo pid,comm,lstart,etime,time,args | grep <进程名或PID>
lstart
:进程启动的具体日期和时间。etime
:进程已运行的总时长(格式为 DD-HH:MM:SS
)。time
:进程消耗的CPU时间(注意不是实际运行时间)。bash
ps -eo pid,comm,lstart,etime,time,args | grep nginx
1234 nginx Mon Oct 2 14:30:00 2023 03:25:10 00:00:45 nginx: worker process
/proc
文件系统ls -ld /proc/<PID>/
bash
pid=1234 # 替换为目标PID
start_time=$(stat -c %Y /proc/$pid)
now=$(date +%s)
seconds=$((now - start_time))
printf "Process has run for: %dd %dh %dm %ds\n" $((seconds/86400)) $((seconds%86400/3600)) $((seconds%3600/60)) $((seconds%60))
top
或 htop
top
:
top
,按 c
显示完整命令,观察 TIME+
列(CPU时间)。TIME+
是CPU占用时间,非实际运行时长。htop
:
sudo apt install htop
(Debian/Ubuntu)或 sudo yum install htop
(RHEL/CentOS)。htop
,在界面中直接查看 TIME+
或启用 STARTTIME
列。systemctl
(仅限系统服务)systemctl show <服务名> --property=ActiveEnterTimestamp
bash
start=$(systemctl show nginx --property=ActiveEnterTimestamp | cut -d= -f2)
now=$(date +%s)
start_epoch=$(date -d "$start" +%s)
echo "Service running for: $(( (now - start_epoch) / 60 )) minutes"
etime
vs TIME
:
etime
:进程从启动到现在的时间(实际运行时长)。TIME
:进程占用CPU的总时间(通常远小于实际时间)。auditd
)或日志查询历史记录。ps -eo pid,comm,lstart,etime | grep <PID>
ps
或 htop
。/proc
或自定义脚本。根据需求选择合适的方法即可获取进程的准确运行时长。