// 181110 created // 200603 rewritten sh version to C to use less CPU when used in tint2 taskbar // - in sync with information shown in top(1) // - uses sysctl kern.cp_time (one statistics for all CPU cores) // - utilization must be calculated by hand every N time slices - TMP file used for storing old values between calculations // - this program is called from tint2 panel every 1 second #include #include #include #include // strtol() #include #include #include #include #include // sleep() #define DEBUG 0 #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_RESET "\x1b[0m" #define dprintf(fmt, ...) \ do { if (DEBUG) printf(ANSI_COLOR_YELLOW "DBG INFO %s:%d %s(): " \ ANSI_COLOR_RESET fmt, __FILE__, __LINE__, __func__,\ ##__VA_ARGS__); } while (0) /* * kern.cp_time * Aggregated CPU state counters for * - user * - nice * - system * - interrupt * - idle * kern.cp_times - as kern.cp_time but for each core * * CPU utilization = user + nice + system + interrupt */ #define CP_USER 0 #define CP_NICE 1 #define CP_SYS 2 #define CP_INTR 3 #define CP_IDLE 4 #define CPUSTATES 5 #define TMP_FILE "/tmp/cpu_usage" bool file_exists(void); void write_old(long str[]); void read_file(void); long cur[CPUSTATES]; long last[CPUSTATES] = {}; bool file_exists(void) { if (access(TMP_FILE, F_OK) != -1) { return 1; } else { return 0; } } void read_file(void) { dprintf("Reading previous state from file\n"); FILE *fp; fp = fopen(TMP_FILE, "r"); for (int state = 0; state calculated utilisation: %.1f cur[CP_IDLE]: %ld last[CP_IDLE]: %ld\n", utilization, cur[CP_IDLE], last[CP_IDLE]); return utilization; } else { printf("should create new file\n"); write_old(cur); return 0.0; // return 0%, will be calculated on next iteration } return utilization; } #ifndef NO_MAIN int main() { double utilization = get_cpu_utilization(); printf("龍%.1f%%\n", utilization); return 0; } #endif // NO_MAIN