Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <stdbool.h>
- #include <sys/wait.h>
- #include <unistd.h>
- int load(FILE *f_proc_stat)
- {
- //declaration of variables to be read from /proc/stat
- const char cpu[3];
- int user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice;
- //variables to be computed in the function
- int cpu_idle, cpu_prev_idle;
- int cpu_nonidle, cpu_prev_nonidle;
- int prev_total, total, total_d, idle_d;
- int cpu_percentage;
- char test[255];
- fgets(test, 255, f_proc_stat);
- sscanf(test, "%s %d %d %d %d %d %d %d %d %d %d", cpu, &user, &nice, &system, &idle, &iowait, &irq, &softirq, &steal, &guest, &guest_nice);
- cpu_prev_nonidle = user + nice + system + irq + softirq + steal;
- cpu_prev_idle = idle + iowait;
- sleep(1);
- fgets(test, 255, f_proc_stat);
- sscanf(test, "%s %d %d %d %d %d %d %d %d %d %d", cpu, &user, &nice, &system, &idle, &iowait, &irq, &softirq, &steal, &guest, &guest_nice);
- /*fscanf(f_proc_stat, "%s %d %d %d %d %d %d %d %d %d %d",
- cpu, &user, &nice, &system, &idle, &iowait, &irq, &softirq,
- &steal, &guest, &guest_nice);*/
- cpu_nonidle = user + nice + system + irq + softirq + steal;
- cpu_idle = idle + iowait;
- prev_total = cpu_prev_idle + cpu_prev_nonidle; total = cpu_idle + cpu_nonidle;
- //differentiate
- total_d = total - prev_total;
- idle_d = cpu_idle - cpu_prev_idle;
- cpu_percentage = (total_d - idle_d)/total_d;
- return cpu_percentage;
- }
- int main() {
- FILE *f_shell_command;
- int refresh_time = 5;
- bool repeat;
- if ((f_shell_command = fopen("/proc/stat", "r")) == NULL)
- {
- fprintf(stderr, "ERROR: Unable to open /proc/stat\n");
- return 1;
- }
- pid_t pid;
- int cpu_percentage;
- pid = fork();
- if (pid == 0)
- {
- while(1)
- {
- cpu_percentage = load(f_shell_command);
- }
- }
- else if (pid < 0)
- {
- fprintf(stderr, "Unable to open process\n");
- return 1;
- }
- else
- {
- do {
- printf("cpu percentage is %d\n", cpu_percentage);
- sleep(refresh_time);
- } while(repeat);
- }
- fclose(f_shell_command);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement