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
|
Net::TcpServer server;
void HandleChildExit(int sig) { signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN);
cout << "子进程" << getpid() << "退出, sig=" << sig << endl;
server.CloseClient(); exit(0); }
void HandleMainExit(int sig) { signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN);
cout << "父进程退出, sig=" << sig << endl;
kill(0, SIGTERM);
server.CloseListener(); exit(0); }
int main(int argc, char *argv[]) {
if (argc != 2) { printf("usage:\n\tServer <port>\n"); return -1; }
for (int i = 1; i <= 64; i++) signal(i, SIG_IGN); signal(SIGTERM, HandleMainExit); signal(SIGINT, HandleMainExit);
if (!server.Init(atoi(argv[1]))) { perror("TcpServer::Init()"); return -1; } cout << "服务器端口: " << argv[1] << endl;
while (true) { if (!server.Accept()) { perror("TcpServer::Accept()"); return -1; }
int pid = fork(); if (pid == -1) { perror("fork"); return -1; } if (pid > 0) { server.CloseClient(); continue; }
server.CloseListener();
signal(SIGTERM, HandleChildExit); signal(SIGINT, SIG_IGN);
cout << "客户端已连接: " << server.GetClientIp() << endl;
string buffer; while (true) { } return 0; } }
|