#include #include #include #include #include #include #define STAT_FILE "/proc/stat" #define OUT_FILE "/tmp/cputild" volatile int running = 1; void signal_handler_sigint(const int _signal) { assert(_signal == SIGINT && "ERROR: Signal except SIGINT received by the SIGINT handler"); printf("hello there\n"); running = 0; } int main(void) { int ret = 0; // register the SIGINT handler signal(SIGINT, signal_handler_sigint); FILE *out_file = fopen(OUT_FILE, "w"); FILE *stat_file = fopen(STAT_FILE, "r"); uint64_t total_jiffies_active = 0; uint64_t total_jiffies_idle = 0; size_t line_len = 1024; char *line_buffer = (char*)malloc(line_len); while (running) { struct timespec now; struct timespec request; struct timespec remain; request.tv_sec = 1; request.tv_nsec = 0; nanosleep(&request, &remain); clock_gettime(CLOCK_REALTIME, &now); fflush(stat_file); fseek(stat_file, 0, SEEK_SET); const ssize_t read = getline(&line_buffer, &line_len, stat_file); if (read == -1) { printf("Failed to read the stat file!\n"); ret = 1; goto exit_label; } uint64_t user, user_nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice; const int n_read = sscanf(line_buffer, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user, &user_nice, &system, &idle, &iowait, &irq, &softirq, &steal, &guest, &guest_nice); // NOLINT(*-err34-c) if (n_read != 10) { printf("Failed to read the stat file: Invalid format?\n"); ret = 1; goto exit_label; } const uint64_t current_total_jiffies_active = user + user_nice + system + irq + softirq + guest + guest_nice; const uint64_t current_total_jiffies_idle = iowait + idle; const uint64_t delta_jiffies_active = current_total_jiffies_active - total_jiffies_active; const uint64_t delta_jiffies_idle = current_total_jiffies_idle - total_jiffies_idle; const double utilization = (double)(delta_jiffies_active) / (double)(delta_jiffies_idle + delta_jiffies_active); total_jiffies_active = current_total_jiffies_active; total_jiffies_idle = current_total_jiffies_idle; out_file = freopen(OUT_FILE, "w", out_file); fseek(out_file, 0, SEEK_SET); fprintf(out_file, "%.02f", utilization * 100); fflush(out_file); } exit_label: free(line_buffer); printf("Terminating...\n"); return ret; }