I need to know which processes are running more than 6 hours in UNIX. How can I find those out?
4 Answers
Depending on what you have available the general approach might be:
ps -o pid,lstart
and run a for loop over the results using something like:
date -j -f %c "$sdate" +%s
to convert the date to a UNIX timestamp. From there something like:
time=$((`date +%s`-`date -j -f %c "$sdate" +%s`))
echo $time
should give you the number of seconds that the process has been running. converting to hours is then trivial.
The short and long is that you will end up writing a script.
You can use following function to Get Process elapse time in minutes
GetProcTime() {
local p=$1
ps -eao "%C %U %c %t" |
awk "/$p/"'{print $4}' |
awk -F":" '{{a=$1*60} {b=a+$2}; if ( NF != 2 ) print b ; else print $1 }'
}
Test
root@ubuntu:/tmp# GetProcTime monit
10
root@ubuntu:/tmp# if [[ $(GetProcTime monit) -ge 360 ]]; then echo "Process is running more than 6 hrs"; else echo "OK"; fi
OK
root@ubuntu:/tmp# GetProcTime init
466
root@ubuntu:/tmp# if [[ $(GetProcTime init) -ge 360 ]]; then echo "Process is running more than 6 hrs"; else echo "OK"; fi
Process is running more than 6 hrs
this command will output process which running more than n hour from yesterday. Process scans only today's processes.
ps -Ao ppid,pid,user,stime,cmd --sort=-pcpu | awk -v dateee=$(date +%H) '{ if (substr($4,3,1) ==":" && ( dateee-substr($4,1,2) > 5 )) print }'
you can change below part according your requirement. Example 5 hour.
dateee-substr($4,1,2) > 5 )
POSIXly, and in the C/POSIX locale, you should be able to rely on ps -o etime giving you the elapsed time in a format like [dd-]hh:mm:ss. So processes that have been running for at least 6 hours would be the ones where there is a non-zero dd- part or when the hh part is greater than 06, so:
LC_ALL=C ps -Ao etime,pid |
LC_ALL=C awk '$1 ~ /[1-9].*-|([1-9].|0[6-9]):..:/ {print $2}'
Would report the pids of the processes that have been running for more than 6 hours.
Note that a process can (and often does) run more than one command in its lifetime.
ps auxshow the columnSTARTwith the start time or date.