Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I need to get %CPU usage of process , I tried following method on Redhat 7.3 Linux 2.4.18-3
1. read /proc/<PID>/stat (utime) entry and save in val1
2. read same /proc/<PID>/stat (utime) entry after 5 seconds and store in val2
3. calculate by using (val2 - val1) / 500 (since jiffies is 1/100 of second).
Does this make any sense.
But when I look at command output of ps -auxw, %CPU usage is about 50-60%(for eg) for daemons (i.e., <PID> above method).
This is a different value than I calculated using above method.
Please let me know
1. if above method is not correct, let me know correct method to calculate %CPU usage of process.
2. Is there any IOCTL calls to process management in Linux where i can get automated value of %CPU usage.
DESCRIPTION
top displays an ongoing sample of system usage statistics. It operates
in various modes, but by default shows cpu utilization and memory usage
for each process in the system.
But I need to get the value of %CPU usage of process specified by PID programmatically
not from command line.
My above method is in reference to linux mailing lists and has drawbacks of sleeping for 5 seconds.
I have other idea for this using popen() and fread().
for eg command name --> xxx, its PID --> yyy.
FILE * fp;char buf[1024];
char * cmd =" ps -C xxx -o yyy=-eo\"%C %x %t %a\"";
fp = popen(cmd,"r");
fread(buf,1,sizeof(buf),fp);
Now buf has instant value of %CPU usage.Is this OK..
But I feel using command strings in application programs is not good practice.
Using API s or IOCTL is considered as good practice.
Is there any other idea??.
I'm also working on to find %CPU usage of a particular process. My problem is just a little more complex, i'm trying to find Peak CPU usage and average CPU usage of a particular process. I also want to do it programmatically and not from command line.
So did u ever figured out how to do it, if yes, could you share the solution with me.
Hello,
have you done something with C programming %CPU utilization?
I need to know how to do it, "top" source code is so big for me...
For the moment i'm using ps to get it, output it and parse it later to extract cpu and memory utilization, but ps is not so accurate as i hoped. I mean there are BIG differences between output of ps and top in cpu utilization...Don't know what to do.
in FEDORACORE they have the option called "SYSTEM MONITER" : i dont acatly remember where though
HI,
that's the problem, i need something that should run in the background on all UNIX platforms ( AIX, HPUX, Solaris, MacOSX and Linux ), at least one version of file ( script or c code ) for each of these platforms.
I have examples were ps -eo comm,pcpu | grep program_name is returning something like :
program_name 1 ( that means 1% CPU utilization, isn't so? )
and when top -b -n 1 | grep program_name it returns ~60% in CPU utilization.....
That's why i think ( looked over top3.5 source code ) that "top" is more accurate then "ps".
Please if somebody has an opinion ( with examples ofcourse , post it!
I've writted a little script to control the cpu usage by a process.
Here's the code:
-----------------------------------------
Code:
#!/bin/bash
#
# Control de procesos
#
# El script controla que el <proceso> no consuma más cpu del <límite>
# Si se sobrepasa el límite el script mata el proceso y acaba.
#
# Para linux kernels 2.6.x
# v.0.1 sept-2007
#
# Autor: Miguel Ángel Molina Molina
# Licencia: GPL v.2
# Check de parámetros
# El parámetro debug es opcional y puede ser cualquier cosa. Si existe, se imprime salida por pantalla para depuración o pruebas
if [ $# -lt 2 -o $# -gt 3 ];
then
echo "Uso: `basename $0` <proceso> <límite> [debug]"
exit -1
fi
# existe debug?
if [ $# -eq 3 ];
then
debug="si"
else
debug=""
fi
procpid=`pidof $1`
typeset -i limite=$2
# Check de existencia del proceso
if [ -z "$procpid" ];
then
echo "El proceso: $1 no existe"
exit -1
fi
# Check del límite
if [ $limite -lt 1 -o $limite -gt 99 ];
then
echo "Límite debe estar entre 1 y 99"
exit -1
fi
typeset -i hits=0
while [ 1 ]
do
# obtengo tiempo de utilización de cpu
typeset -i cputime=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
# check del pid del proceso
if [ ! -f /proc/${procpid}/stat ];
then
echo "No existe el proceso: ${procpid}"
exit -1
fi
# obtengo tiempo de uso de cpu por el proceso
typeset -i proctime=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
# espero 5 segundos
sleep 5
# vuelvo a obtener tiempo de utilización de cpu
typeset -i cputime2=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
# vuelvo a obtener tiempo de uso de cpu por el proceso
typeset -i proctime2=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
# calculo el porcentaje que supone el tiempo de uso de cpu del proceso respecto al tiempo total de cpu
typeset -i cpu=$((($proctime2-$proctime)*100/($cputime2-$cputime)))
[ ! -z $debug ] && echo "El proceso $1, con pid: $procpid, está consumiendo: $cpu% de cpu"
# check de límite sobrepasado
if [ $cpu -gt $limite ];
then
# cuento los sobrepasamientos
let hits+=1
if [ $hits = 1 ];
then
veces="vez"
else
veces="veces"
fi
[ ! -z $debug ] && echo "El proceso $1 ha sobrepasado el límite: $limite ($cpu) $hits $veces ..."
# si ha superado los 10 sobrepasamientos, mato el proceso
if [ $hits -gt 10 ];
then
echo -n "Matando proceso: $procpid ... "
kill $procpid
# espero a que el proceso muera
sleep 1
# check para comprobar si ha muerto el proceso
if [ -z "`pidof $1`" ];
then
echo "Hecho."
else
echo "No se ha podido matar el proceso."
fi
echo "Finalizado."
exit 0
fi
else
# si no sobrepasa el límite, pongo a cero el contador
let hits=0
fi
done
-----------------------------------------
I hope it may be useful.
I would like to receive your comments.
P.S.: Sorry, I haven't translated it to english yet.
#!/bin/bash
#
# Process control
#
# This shell-script watch that <process> doesn't pass the <limit> of % cpu usage
# If it does, the script kills that process and finish
#
# For linux kernel 2.6.x
# v.0.1 sept-2007
#
# Author: Miguel Ángel Molina Molina
# Licence: GPL v.2
# Parameter check
# [debug] parameter is optional and can be anything. If it exists, the script produces output to the screen for debugging purposes.
if [ $# -lt 2 -o $# -gt 3 ];
then
echo "Usage: `basename $0` <process> <limit> [debug]"
exit -1
fi
# [debug] exists?
if [ $# -eq 3 ];
then
debug="yes"
else
debug=""
fi
procpid=`pidof $1`
typeset -i limit=$2
# process existence check
if [ -z "$procpid" ];
then
echo "Process: $1 doesn't exists"
exit -1
fi
# limit check
if [ $limit -lt 1 -o $limit -gt 99 ];
then
echo "Limit must be between 1 and 99"
exit -1
fi
typeset -i hits=0
while [ 1 ]
do
# Get usage cpu time
typeset -i cputime=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
# process pid check
if [ ! -f /proc/${procpid}/stat ];
then
echo "Process doesn't exists: ${procpid}"
exit -1
fi
# Get process usage cpu time
typeset -i proctime=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
# wait 5 seconds
sleep 5
# get usage cpu time, again
typeset -i cputime2=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
# get process usage cpu time, again
typeset -i proctime2=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
# calculate process usage cpu time over total usage cpu time as percentage
typeset -i cpu=$((($proctime2-$proctime)*100/($cputime2-$cputime)))
[ ! -z $debug ] && echo "Process $1, with pid: $procpid, is wasting: $cpu% of cpu"
# limit exceed check
if [ $cpu -gt $limit ];
then
# Count the excess
let hits+=1
if [ $hits = 1 ];
then
times="time"
else
times="times"
fi
[ ! -z $debug ] && echo "Process $1 has exceeded the limit: $limit ($cpu) $hits $times ..."
# If hits are greater than 10, kill the process
if [ $hits -gt 10 ];
then
echo -n "Killing process: $procpid ... "
kill $procpid
# wait until process die
sleep 1
# check if process has died
if [ -z "`pidof $1`" ];
then
echo "Done."
else
echo "Can't kill the process."
fi
echo "Finished."
exit 0
fi
else
# if no limit exceed, reset hit counter
let hits=0
fi
done
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.