FILE *file;
unsigned proc_count = 0;
long cpu = 0, nice = 0, system = 0, idle = 0, used = 0, total = 0;
char buff[MAXBUFF];
char *lpbuff = buff;
size_t n = 0;
char s_cpu_usage[MAXBUFF];
bzero(s_cpu_usage, MAXBUFF);
strcpy(s_cpu_usage, "");
proc_count = get_nprocs();
file = fopen("/proc/stat", "r");
if(!file)
{
sprintf(msg->error_str, "Error when getting CPU statistics. errno(%d) : %s", errno, strerror(errno));
return 0;
}
//
getline(&lpbuff, &n, file);
for (i = 0; i < proc_count; i++)
{
fscanf(file, "%*s %ld %ld %ld %ld", &cpu, &nice, &system, &idle);
used = cpu+nice+system;
total = cpu+nice+system+idle;
bzero(buff, MAXBUFF);
sprintf(lpbuff, "%ld %ld\n", used, total);
strcat(s_cpu_usage, lpbuff);
}
fclose(file);
FILE *file;
unsigned proc_count = 0;
long cpu = 0, nice = 0, system = 0, idle = 0, used = 0, total = 0;
char buff[MAXBUFF];
char *lpbuff = buff;
size_t n = 0;
char s_cpu_usage[MAXBUFF];
bzero(s_cpu_usage, MAXBUFF);
strcpy(s_cpu_usage, "");
proc_count = get_nprocs();
file = fopen("/proc/stat", "r");
if(!file)
{
sprintf(msg->error_str, "Error when getting CPU statistics. errno(%d) : %s", errno, strerror(errno));
return 0;
}
//
getline(&lpbuff, &n, file);
for (i = 0; i < proc_count; i++)
{
fscanf(file, "%*s %ld %ld %ld %ld", &cpu, &nice, &system, &idle);
used = cpu+nice+system;
total = cpu+nice+system+idle;
bzero(buff, MAXBUFF);
sprintf(lpbuff, "%ld %ld\n", used, total);
strcat(s_cpu_usage, lpbuff);
}
fclose(file);
To copy to clipboard, switch view to plain text mode
This is a part from one of my functions. I've corrected it slightly but I hope it will be clear for you.
Bookmarks