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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
| #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <poll.h> #include <signal.h> #include <time.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> #include <getopt.h>
// 服务器配置结构体 struct server_config { int port; int max_clients; int timeout_seconds; int verbose; int use_signals; char *log_file; };
// 客户端信息结构体 struct client_info { int fd; int connected; time_t connect_time; char buffer[1024]; size_t buffer_pos; };
// 服务器状态结构体 struct server_state { int running; int client_count; struct client_info *clients; int max_clients; FILE *log_fp; };
// 全局变量 volatile sig_atomic_t server_terminate = 0; volatile sig_atomic_t server_reload = 0;
// 信号处理函数 void signal_handler(int sig) { switch (sig) { case SIGINT: case SIGTERM: printf("\n收到终止信号,准备关闭服务器...\n"); server_terminate = 1; break; case SIGHUP: printf("\n收到重载信号,重新加载配置...\n"); server_reload = 1; break; case SIGUSR1: printf("\n收到用户信号 1\n"); break; case SIGUSR2: printf("\n收到用户信号 2\n"); break; } }
// 设置信号处理 void setup_server_signals() { struct sigaction sa; sa.sa_handler = signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGUSR1, &sa, NULL); sigaction(SIGUSR2, &sa, NULL); }
// 初始化服务器状态 int init_server_state(struct server_state *state, int max_clients) { state->running = 1; state->client_count = 0; state->max_clients = max_clients; state->clients = calloc(max_clients, sizeof(struct client_info)); if (!state->clients) { perror("分配客户端数组失败"); return -1; } state->log_fp = stderr; // 默认输出到标准错误 return 0; }
// 添加客户端 int add_client(struct server_state *state, int client_fd) { if (state->client_count >= state->max_clients) { fprintf(stderr, "客户端数量已达上限: %d\n", state->max_clients); return -1; } for (int i = 0; i < state->max_clients; i++) { if (!state->clients[i].connected) { state->clients[i].fd = client_fd; state->clients[i].connected = 1; state->clients[i].connect_time = time(NULL); state->clients[i].buffer_pos = 0; state->client_count++; printf("添加客户端 %d (fd: %d),当前客户端数: %d\n", i, client_fd, state->client_count); return i; } } fprintf(stderr, "找不到空闲的客户端槽位\n"); return -1; }
// 移除客户端 void remove_client(struct server_state *state, int client_index) { if (client_index >= 0 && client_index < state->max_clients && state->clients[client_index].connected) { close(state->clients[client_index].fd); memset(&state->clients[client_index], 0, sizeof(struct client_info)); state->client_count--; printf("移除客户端 %d,剩余客户端数: %d\n", client_index, state->client_count); } }
// 处理客户端数据 void handle_client_data(struct server_state *state, int client_index) { struct client_info *client = &state->clients[client_index]; // 模拟读取客户端数据 char buffer[256]; ssize_t bytes_read = read(client->fd, buffer, sizeof(buffer) - 1); if (bytes_read > 0) { buffer[bytes_read] = '\0'; printf("客户端 %d 发送数据: %s", client_index, buffer); // 回显数据 write(client->fd, "Echo: ", 6); write(client->fd, buffer, bytes_read); } else if (bytes_read == 0) { printf("客户端 %d 断开连接\n", client_index); remove_client(state, client_index); } else { if (errno != EAGAIN && errno != EWOULDBLOCK) { perror("读取客户端数据失败"); remove_client(state, client_index); } } }
// 显示服务器状态 void show_server_status(const struct server_state *state) { printf("=== 服务器状态 ===\n"); printf("运行状态: %s\n", state->running ? "运行中" : "已停止"); printf("客户端数量: %d/%d\n", state->client_count, state->max_clients); printf("当前时间: %s", ctime(&(time_t){time(NULL)})); if (state->client_count > 0) { printf("连接的客户端:\n"); for (int i = 0; i < state->max_clients; i++) { if (state->clients[i].connected) { printf(" [%d] fd=%d 连接时间: %s", i, state->clients[i].fd, ctime(&state->clients[i].connect_time)); } } } printf("\n"); }
// 模拟服务器主循环 int run_server_simulation(struct server_state *state, const struct server_config *config) { struct pollfd *fds = NULL; struct timespec timeout; sigset_t sigmask; int ready; printf("启动服务器模拟...\n"); printf("最大客户端数: %d\n", config->max_clients); printf("超时时间: %d 秒\n", config->timeout_seconds); printf("使用信号处理: %s\n", config->use_signals ? "是" : "否"); printf("\n"); // 分配 pollfd 数组 (1个用于标准输入 + 最大客户端数) fds = calloc(1 + config->max_clients, sizeof(struct pollfd)); if (!fds) { perror("分配 pollfd 数组失败"); return -1; } // 初始化标准输入监视 fds[0].fd = STDIN_FILENO; fds[0].events = POLLIN; fds[0].revents = 0; // 设置超时时间 timeout.tv_sec = config->timeout_seconds; timeout.tv_nsec = 0; // 设置信号屏蔽集 sigemptyset(&sigmask); if (!config->use_signals) { // 如果不使用信号,可以屏蔽一些信号 sigaddset(&sigmask, SIGUSR1); sigaddset(&sigmask, SIGUSR2); } // 显示初始状态 show_server_status(state); // 主循环 while (state->running && !server_terminate) { // 更新 pollfd 数组 int nfds = 1; // 至少包含标准输入 // 添加连接的客户端 for (int i = 0; i < state->max_clients; i++) { if (state->clients[i].connected) { fds[nfds].fd = state->clients[i].fd; fds[nfds].events = POLLIN; fds[nfds].revents = 0; nfds++; } } if (config->verbose) { printf("监视 %d 个文件描述符...\n", nfds); } // 使用 ppoll 等待事件 ready = ppoll(fds, nfds, &timeout, &sigmask); if (ready == -1) { if (errno == EINTR) { if (config->verbose) { printf("ppoll 被信号中断\n"); } if (server_reload) { printf("重新加载配置...\n"); server_reload = 0; } continue; } else { perror("ppoll 失败"); break; } } else if (ready == 0) { if (config->verbose) { printf("超时: 没有事件发生\n"); } } else { if (config->verbose) { printf("准备就绪的文件描述符数量: %d\n", ready); } // 处理事件 for (int i = 0; i < nfds; i++) { if (fds[i].revents & POLLIN) { if (i == 0) { // 标准输入事件 char input_buffer[256]; ssize_t bytes_read = read(STDIN_FILENO, input_buffer, sizeof(input_buffer) - 1); if (bytes_read > 0) { input_buffer[bytes_read] = '\0'; // 处理特殊命令 if (strncmp(input_buffer, "quit", 4) == 0 || strncmp(input_buffer, "exit", 4) == 0) { printf("收到退出命令\n"); state->running = 0; server_terminate = 1; } else if (strncmp(input_buffer, "status", 6) == 0) { show_server_status(state); } else if (strncmp(input_buffer, "help", 4) == 0) { printf("可用命令:\n"); printf(" quit/exit - 退出服务器\n"); printf(" status - 显示服务器状态\n"); printf(" help - 显示帮助信息\n"); printf(" Ctrl+C - 发送终止信号\n"); } else { printf("收到输入: %s", input_buffer); // 模拟添加客户端 if (strncmp(input_buffer, "connect", 7) == 0) { if (state->client_count < state->max_clients) { // 模拟创建客户端连接 int fake_fd = 1000 + state->client_count; int client_index = add_client(state, fake_fd); if (client_index != -1) { printf("模拟客户端连接成功 (fd: %d)\n", fake_fd); } } else { printf("客户端数量已达上限\n"); } } } } } else { // 客户端事件 int client_fd = fds[i].fd; int client_index = -1; // 查找对应的客户端 for (int j = 0; j < state->max_clients; j++) { if (state->clients[j].connected && state->clients[j].fd == client_fd) { client_index = j; break; } } if (client_index != -1) { handle_client_data(state, client_index); } else { printf("未知客户端事件 (fd: %d)\n", client_fd); } } } if (fds[i].revents & (POLLERR | POLLHUP | POLLNVAL)) { printf("文件描述符 %d 发生异常\n", fds[i].fd); if (i > 0) { // 客户端异常 int client_fd = fds[i].fd; for (int j = 0; j < state->max_clients; j++) { if (state->clients[j].connected && state->clients[j].fd == client_fd) { remove_client(state, j); break; } } } } } } // 重置 revents for (int i = 0; i < nfds; i++) { fds[i].revents = 0; } } // 清理资源 free(fds); // 关闭所有客户端连接 for (int i = 0; i < state->max_clients; i++) { if (state->clients[i].connected) { remove_client(state, i); } } printf("服务器模拟结束\n"); return 0; }
// 显示帮助信息 void show_help(const char *program_name) { printf("用法: %s [选项]\n", program_name); printf("\n选项:\n"); printf(" -p, --port=PORT 监听端口 (默认 8080)\n"); printf(" -c, --clients=NUM 最大客户端数 (默认 10)\n"); printf(" -t, --timeout=SECONDS 超时时间 (默认 30 秒)\n"); printf(" -v, --verbose 详细输出\n"); printf(" -s, --signals 启用信号处理\n"); printf(" -l, --log=FILE 日志文件\n"); printf(" -h, --help 显示此帮助信息\n"); printf("\n示例:\n"); printf(" %s # 使用默认设置运行\n", program_name); printf(" %s -c 20 -t 60 -v # 20个客户端,60秒超时,详细输出\n", program_name); printf(" %s -s -l server.log # 启用信号处理,记录日志\n", program_name); printf(" %s --help # 显示帮助信息\n", program_name); }
int main(int argc, char *argv[]) { struct server_config config = { .port = 8080, .max_clients = 10, .timeout_seconds = 30, .verbose = 0, .use_signals = 0, .log_file = NULL }; struct server_state server_state_struct; printf("=== ppoll 事件驱动服务器模拟器 ===\n\n"); // 解析命令行参数 static struct option long_options[] = { {"port", required_argument, 0, 'p'}, {"clients", required_argument, 0, 'c'}, {"timeout", required_argument, 0, 't'}, {"verbose", no_argument, 0, 'v'}, {"signals", no_argument, 0, 's'}, {"log", required_argument, 0, 'l'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; int opt; while ((opt = getopt_long(argc, argv, "p:c:t:vsl:h", long_options, NULL)) != -1) { switch (opt) { case 'p': config.port = atoi(optarg); break; case 'c': config.max_clients = atoi(optarg); if (config.max_clients <= 0) config.max_clients = 10; break; case 't': config.timeout_seconds = atoi(optarg); if (config.timeout_seconds <= 0) config.timeout_seconds = 30; break; case 'v': config.verbose = 1; break; case 's': config.use_signals = 1; break; case 'l': config.log_file = optarg; break; case 'h': show_help(argv[0]); return 0; default: fprintf(stderr, "使用 '%s --help' 查看帮助信息\n", argv[0]); return 1; } } // 设置信号处理 if (config.use_signals) { setup_server_signals(); printf("✓ 信号处理已启用\n"); } // 初始化服务器状态 if (init_server_state(&server_state_struct, config.max_clients) == -1) { return 1; } // 设置日志文件 if (config.log_file) { server_state_struct.log_fp = fopen(config.log_file, "a"); if (server_state_struct.log_fp) { printf("✓ 日志文件: %s\n", config.log_file); } else { perror("打开日志文件失败"); config.log_file = NULL; server_state_struct.log_fp = stderr; } } printf("服务器配置:\n"); printf(" 监听端口: %d\n", config.port); printf(" 最大客户端数: %d\n", config.max_clients); printf(" 超时时间: %d 秒\n", config.timeout_seconds); printf(" 详细输出: %s\n", config.verbose ? "是" : "否"); printf(" 信号处理: %s\n", config.use_signals ? "是" : "否"); printf(" 日志文件: %s\n", config.log_file ? config.log_file : "标准错误"); printf("\n"); printf("启动服务器模拟...\n"); printf("可用命令:\n"); printf(" 输入 'status' 查看服务器状态\n"); printf(" 输入 'connect' 模拟客户端连接\n"); printf(" 输入 'quit' 或 'exit' 退出服务器\n"); printf(" 输入 'help' 显示帮助信息\n"); printf(" 按 Ctrl+C 发送终止信号\n"); printf("\n"); // 运行服务器模拟 int result = run_server_simulation(&server_state_struct, &config); // 清理资源 if (server_state_struct.clients) { free(server_state_struct.clients); } if (config.log_file && server_state_struct.log_fp != stderr) { fclose(server_state_struct.log_fp); } printf("\n=== ppoll 服务器应用说明 ===\n"); printf("核心技术:\n"); printf("1. 多路复用: 同时监视多个文件描述符\n"); printf("2. 事件驱动: 基于事件的通知机制\n"); printf("3. 信号安全: 原子的信号处理\n"); printf("4. 超时控制: 精确的超时管理\n"); printf("5. 资源管理: 动态的客户端管理\n"); printf("\n"); printf("ppoll 优势:\n"); printf("1. 原子性: 等待和信号处理是原子操作\n"); printf("2. 灵活性: 可以精确控制信号屏蔽\n"); printf("3. 精确性: 纳秒级超时控制\n"); printf("4. 可扩展: 无文件描述符数量限制\n"); printf("5. 安全性: 避免信号处理中的竞态条件\n"); printf("\n"); printf("实际应用场景:\n"); printf("1. 网络服务器: HTTP/WebSocket 服务器\n"); printf("2. 代理服务: 反向代理、负载均衡\n"); printf("3. 实时应用: 游戏服务器、聊天应用\n"); printf("4. 监控系统: 系统监控、日志收集\n"); printf("5. 数据处理: 流数据处理、ETL 系统\n"); return result; }
|