1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
| #include <sys/times.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/wait.h> #include <time.h> #include <signal.h>
/** * CPU监控数据结构 */ typedef struct { time_t timestamp; clock_t ticks; struct tms tms_data; double cpu_usage_percent; double user_cpu_percent; double system_cpu_percent; double children_cpu_percent; } cpu_monitor_data_t;
/** * CPU监控器结构 */ typedef struct { cpu_monitor_data_t history[100]; // 历史数据 int history_count; int max_history; long clk_tck; volatile int monitoring; pid_t target_pid; // 监控特定进程(0表示当前进程) } cpu_monitor_t;
/** * 初始化CPU监控器 */ int init_cpu_monitor(cpu_monitor_t *monitor, pid_t target_pid) { memset(monitor, 0, sizeof(cpu_monitor_t)); monitor->max_history = 100; monitor->clk_tck = sysconf(_SC_CLK_TCK); monitor->target_pid = target_pid; monitor->monitoring = 1; if (monitor->clk_tck == -1) { perror("获取系统滴答率失败"); return -1; } printf("CPU监控器初始化完成\n"); printf(" 监控目标: %s\n", target_pid ? "特定进程" : "当前进程"); printf(" 系统滴答率: %ld 滴答/秒\n", monitor->clk_tck); return 0; }
/** * 收集CPU使用数据 */ int collect_cpu_data(cpu_monitor_t *monitor) { if (monitor->history_count >= monitor->max_history) { // 循环覆盖旧数据 memmove(&monitor->history[0], &monitor->history[1], sizeof(cpu_monitor_data_t) * (monitor->max_history - 1)); monitor->history_count = monitor->max_history - 1; } cpu_monitor_data_t *current = &monitor->history[monitor->history_count]; current->timestamp = time(NULL); current->ticks = times(¤t->tms_data); if (current->ticks == (clock_t)-1) { perror("获取CPU时间失败"); return -1; } // 计算CPU使用率(与前一个采样点比较) if (monitor->history_count > 0) { cpu_monitor_data_t *previous = &monitor->history[monitor->history_count - 1]; clock_t ticks_diff = current->ticks - previous->ticks; if (ticks_diff > 0) { clock_t utime_diff = current->tms_data.tms_utime - previous->tms_data.tms_utime; clock_t stime_diff = current->tms_data.tms_stime - previous->tms_data.tms_stime; clock_t cutime_diff = current->tms_data.tms_cutime - previous->tms_data.tms_cutime; clock_t cstime_diff = current->tms_data.tms_cstime - previous->tms_data.tms_cstime; current->user_cpu_percent = (double)utime_diff / ticks_diff * 100; current->system_cpu_percent = (double)stime_diff / ticks_diff * 100; current->children_cpu_percent = (double)(cutime_diff + cstime_diff) / ticks_diff * 100; current->cpu_usage_percent = current->user_cpu_percent + current->system_cpu_percent + current->children_cpu_percent; } else { current->cpu_usage_percent = 0.0; current->user_cpu_percent = 0.0; current->system_cpu_percent = 0.0; current->children_cpu_percent = 0.0; } } else { // 第一次采样,无法计算使用率 current->cpu_usage_percent = 0.0; current->user_cpu_percent = 0.0; current->system_cpu_percent = 0.0; current->children_cpu_percent = 0.0; } monitor->history_count++; return 0; }
/** * 显示CPU监控数据 */ void show_cpu_monitor_data(const cpu_monitor_t *monitor) { if (monitor->history_count == 0) { printf("暂无监控数据\n"); return; } const cpu_monitor_data_t *latest = &monitor->history[monitor->history_count - 1]; printf("=== CPU监控数据 ===\n"); printf("采样时间: %s", ctime(&latest->timestamp)); printf("CPU使用率: %.2f%%\n", latest->cpu_usage_percent); printf(" 用户态: %.2f%%\n", latest->user_cpu_percent); printf(" 系统态: %.2f%%\n", latest->system_cpu_percent); printf(" 子进程: %.2f%%\n", latest->children_cpu_percent); // 显示详细时间信息 printf("详细时间信息:\n"); printf(" 用户态时间: %.3f 秒\n", (double)latest->tms_data.tms_utime / monitor->clk_tck); printf(" 系统态时间: %.3f 秒\n", (double)latest->tms_data.tms_stime / monitor->clk_tck); printf(" 子进程用户态时间: %.3f 秒\n", (double)latest->tms_data.tms_cutime / monitor->clk_tck); printf(" 子进程系统态时间: %.3f 秒\n", (double)latest->tms_data.tms_cstime / monitor->clk_tck); }
/** * 显示历史趋势 */ void show_cpu_trend(const cpu_monitor_t *monitor) { if (monitor->history_count < 2) { printf("数据不足,无法显示趋势\n"); return; } printf("=== CPU使用率趋势 ===\n"); printf("%-20s %-8s %-8s %-8s %-8s\n", "时间", "总CPU%", "用户%", "系统%", "子进程%"); printf("%-20s %-8s %-8s %-8s %-8s\n", "----", "------", "----", "----", "-----"); // 显示最近10个采样点 int start_index = (monitor->history_count > 10) ? monitor->history_count - 10 : 0; for (int i = start_index; i < monitor->history_count; i++) { const cpu_monitor_data_t *data = &monitor->history[i]; char time_str[20]; strftime(time_str, sizeof(time_str), "%H:%M:%S", localtime(&data->timestamp)); printf("%-20s %-8.1f %-8.1f %-8.1f %-8.1f\n", time_str, data->cpu_usage_percent, data->user_cpu_percent, data->system_cpu_percent, data->children_cpu_percent); } }
/** * 模拟被监控的工作进程 */ void work_process(int work_id) { printf("工作进程 %d (PID: %d) 启动\n", work_id, getpid()); // 执行不同类型的工作 for (int cycle = 0; cycle < 5; cycle++) { printf("工作进程 %d: 执行周期 %d\n", work_id, cycle + 1); // CPU密集型工作 volatile long sum = 0; for (long i = 0; i < 50000000; i++) { sum += i; } printf(" CPU工作完成,结果: %ld\n", sum); // I/O工作 char filename[64]; snprintf(filename, sizeof(filename), "/tmp/work_%d_cycle_%d.tmp", work_id, cycle); FILE *fp = fopen(filename, "w"); if (fp) { for (int i = 0; i < 10000; i++) { fprintf(fp, "工作数据 %d.%d\n", cycle, i); } fclose(fp); unlink(filename); } sleep(2); // 休息一下 } printf("工作进程 %d 完成\n", work_id); exit(work_id); }
/** * 演示实时CPU监控 */ int demo_real_time_cpu_monitoring() { cpu_monitor_t monitor; pid_t worker_pids[2]; int worker_count = 2; printf("=== 实时CPU监控演示 ===\n"); // 初始化监控器 if (init_cpu_monitor(&monitor, 0) != 0) { return -1; } // 创建工作进程 printf("创建 %d 个工作进程:\n", worker_count); for (int i = 0; i < worker_count; i++) { worker_pids[i] = fork(); if (worker_pids[i] == 0) { work_process(i + 1); } else if (worker_pids[i] > 0) { printf(" 工作进程 %d: PID=%d\n", i + 1, worker_pids[i]); } else { perror("创建工作进程失败"); for (int j = 0; j < i; j++) { kill(worker_pids[j], SIGKILL); } return -1; } } // 开始监控 printf("\n开始实时监控 (30秒):\n"); time_t start_time = time(NULL); while (difftime(time(NULL), start_time) < 30) { // 收集CPU数据 if (collect_cpu_data(&monitor) != 0) { printf("收集CPU数据失败\n"); break; } // 每5秒显示一次详细信息 if (((int)difftime(time(NULL), start_time)) % 5 == 0) { show_cpu_monitor_data(&monitor); // 每15秒显示一次趋势 if (((int)difftime(time(NULL), start_time)) % 15 == 0) { show_cpu_trend(&monitor); } printf("---\n"); } // 短暂休眠 usleep(500000); // 500ms } // 等待工作进程完成 printf("等待工作进程完成:\n"); for (int i = 0; i < worker_count; i++) { int status; pid_t finished_pid = waitpid(worker_pids[i], &status, 0); if (finished_pid > 0) { printf(" 工作进程 %d (PID=%d) 已完成,退出状态: %d\n", WEXITSTATUS(status), finished_pid, WEXITSTATUS(status)); } } // 显示最终监控结果 printf("\n=== 最终监控结果 ===\n"); // 收集最终数据 collect_cpu_data(&monitor); show_cpu_monitor_data(&monitor); // 显示完整趋势 printf("\n完整CPU使用率趋势:\n"); show_cpu_trend(&monitor); // 统计分析 if (monitor.history_count > 1) { double max_cpu = 0, min_cpu = 100, avg_cpu = 0; double total_cpu = 0; int valid_samples = 0; for (int i = 1; i < monitor.history_count; i++) { double cpu_usage = monitor.history[i].cpu_usage_percent; if (cpu_usage >= 0) { // 有效数据 if (cpu_usage > max_cpu) max_cpu = cpu_usage; if (cpu_usage < min_cpu) min_cpu = cpu_usage; total_cpu += cpu_usage; valid_samples++; } } if (valid_samples > 0) { avg_cpu = total_cpu / valid_samples; printf("\n=== 统计分析 ===\n"); printf("CPU使用率统计:\n"); printf(" 最高使用率: %.2f%%\n", max_cpu); printf(" 最低使用率: %.2f%%\n", min_cpu); printf(" 平均使用率: %.2f%%\n", avg_cpu); if (avg_cpu > 80) { printf(" 🚨 警告: 平均CPU使用率过高\n"); } else if (avg_cpu > 60) { printf(" ⚠ 提醒: CPU使用率较高\n"); } else { printf(" ✓ CPU使用率正常\n"); } } } return 0; }
int main() { return demo_real_time_cpu_monitoring(); }
|