#include
#include
#include "machine.h"
#define PROCFS "/proc"
#define PROC_SUPER_MAGIC 0x9fa0
/* these are for calculating cpu state percentages */
static long cp_time[NCPUSTATES];
static long cp_old[NCPUSTATES];
static long cp_diff[NCPUSTATES];
static int cpu_states[NCPUSTATES];
char *myname = "cigtop";
static inline char *
skip_token(const char *p)
{
while (isspace(*p)) p++;
while (*p && !isspace(*p)) p++;
return (char *)p;
}
int machine_init(void)
{
/* make sure the proc filesystem is mounted */
struct statfs sb;
if (statfs(PROCFS, &sb) < 0 || sb.f_type != PROC_SUPER_MAGIC)
{
fprintf(stderr, "%s: proc filesystem not mounted on " PROCFS "\n", myname);
return -1;
}
/* chdir to the proc filesystem to make things easier */
// chdir(PROCFS);
return 0;
}
long percentages(int cnt, int *out, long *new, long *old, long *diffs)
{
register int i;
register long change;
register long total_change;
register long *dp;
long half_total;
/* initialization */
total_change = 0;
dp = diffs;
/* calculate changes for each state and the overall change */
for (i = 0; i < cnt; i++)
{
if ((change = *new - *old) < 0)
{
/* this only happens when the counter wraps */
change = (int)
((unsigned long)*new-(unsigned long)*old);
}
total_change += (*dp++ = change);
*old++ = *new++;
}
/* avoid divide by zero potential */
if (total_change == 0)
{
total_change = 1;
}
/* calculate percentages based on overall change, rounding up */
half_total = total_change / 2l;
for (i = 0; i < cnt; i++)
{
*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
}
/* return the total in case the caller wants to use it */
return(total_change);
}
void get_system_info(struct system_info *info)
{
char buffer[4096+1];
int fd, len;
char *p;
/* get the cpu time info */
if ((fd = open("/proc/stat", O_RDONLY)) != -1)
{
if ((len = read(fd, buffer, sizeof(buffer)-1)) > 0)
{
buffer[len] = '\0';
p = skip_token(buffer); /* "cpu" */
cp_time[0] = strtoul(p, &p, 0);
cp_time[1] = strtoul(p, &p, 0);
cp_time[2] = strtoul(p, &p, 0);
cp_time[3] = strtoul(p, &p, 0);
/* convert cp_time counts to percentages */
percentages(NCPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
}
close(fd);
}
/* set arrays and strings */
info->cpustates = cpu_states;
}
////////////////
struct system_info system_info;
machine_init();
while(1)
{
sleep(1);
get_system_info(&system_info);
r_load = ((float)*system_info.cpustates)/10.;
}
No comments :
Post a Comment