Idle time of a process in Linux

这一生的挚爱 提交于 2019-12-04 05:12:11

问题


I need to calculate CPU usage (user mode, system mode, idle time) of a process in Linux. I am able to calculate usage in user and system mode using utime and stime values from /proc/PID/stat, but I found nothing which is related to idle time.

I know I can get idle time from /proc/stat but this value is related to machine, not for particular process.

Is it possible to calculate idle time of a process knowing its PID (reading data from /proc directory)?


回答1:


I don't know much about it but maybe the following works:

1) Get the process start up time. Im sure thats possible
2) Generate time difference (dTime = CurrentTime - TimeProcessStarted)
3) Substract the time the process is running ( dTime - (usageSystemMode + usageUserMode))

Hope this helps! :D




回答2:


it's too late but, I guessed this command useful:

IFS=$'\n';for i in `ps -eo uname:20,pid,cmd | grep -v "USER\|grep\|root"`; \
do if [ $(id -g `echo $i | cut -d" " -f1`) -gt 1000 ] && \
[ $(echo $((($(date +%s) - $(date -d "$(ll -u \ 
--time-style=+"%y-%m-%d %H:%M:%S" /proc/$(echo $i | \
awk '{print $2}')/cwd | awk '{print $6" "$7}')" +%s))/3600))) >=1 ]; \
then echo $i; fi; done

to use it in bash file:

#!/bin/bash
IFS=$'\n'
for i in `ps -eo uname:20,pid,cmd | grep -v "USER\|grep\|root"`
do 
  Name="`echo $i | cut -d' ' -f1`"
  Id="$(id -g $Name)"
  Pid="`echo $i | awk '{print $2}'`"
  Time1=$(date +%s)
  Time2=$(date -d "$(/usr/bin/ls -lu --time-style=+"%y-%m-%d %H:%M:%S" \
 /proc/$Pid/cwd | awk '{print $6" "$7}')" +%s)/3600
  Time=$Time1-$Time2
  if [ $Id -gt 1000 ] && [ $Time >=1 ]
  then 
    echo $i
  fi

done

you could change grep -v "grep\|root" as you wish. this one line command list all processes which not root owner or system users.



来源:https://stackoverflow.com/questions/9053236/idle-time-of-a-process-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!