I have a set of requirement
1)cpu utilization on a server with pid and and process name.
It should display the above and also the script should have an option to record the cpu utilization for a given period of time
first part i can get with below commands
ps -eo pcpu,pid,user,args or top -n 1 -b
how do i record if the user who runs the script want to do it for 5 minutes.
redirect the output of your top command to a file and start that as background process run sleep for 5 mins and then kill the background process.
---------- Post updated at 02:19 PM ---------- Previous update was at 02:17 PM ----------
If you have SAR utility your life would be easy
1 Like
GNU top
takes
- a -n flag which is the number of iterations to run
- a -d flag, which is the delay between iterations
- and a -b flag which streams output suitable for processing
So you could take the user input, set the delay as that interval and iterations to 2, then only use the cpu usage values in the second iteration
1 Like
So will this work?
top -b > ~/op.txt &
sleep $seconds
kill $!
It will, but you will have to parse and aggregate the resulting data, however why not
top -b -d $seconds -n2 | egrep '^Cpu' | tail -1
Which will give you the cpu usage line.
alternatively:
top -b -d $seconds -n2 > top.tmp
split -a1 -l$(( $(wc -l top.tmp| cut -d\ -f1 ) / 2 )) top.tmp top.
cat top.b
rm top.tmp top.a top.b top.c # top.c will be created with a newline character.
For the averages over $seconds for all processes
1 Like