这是我的代码片段:
signal (SIGINT, ( void *)sig_handler);
while(1){
newsockd = -1;
memset(&cli_addr, 0, sizeof(cli_addr));
if((newsockd = accept(sockd, (struct sockaddr *) &cli_addr, (socklen_t *) &socket_len)) < 0){
perror("Errore nella connessione\n");
onexit(newsockd, sockd, 0, 2);
}
fprintf(stdout, "Ricevuta richiesta di connessione dall' indirizzo %s\n", inet_ntoa(cli_addr.sin_addr));
child_pid = fork();
if(child_pid < 0){
perror("Fork error");
onexit(newsockd, sockd, 0, 2);
}
if(child_pid == 0){
do_child(newsockd);
exit(0);
}
else{
while(waitpid(child_pid, NULL, WNOHANG) > 0)
continue;
}
}
}
和函数 sig_handler:
void sig_handler(const int signo, const int sockd, const int newsockd){
if (signo == SIGINT){
printf("Received SIGINT, exiting..\n");
if(newsockd) close(newsockd);
if(sockd) close(sockd);
exit(EXIT_SUCCESS);
}
}
当我按下“CTRL+C”时会出现问题,因为 sighandler 被多次调用。
例子:
- 服务器正在监听;
- 2 x 收到连接;
- 2 个儿童叉;
- 2 x 孩子已关闭;
- 现在我想关闭服务器,所以我按 CTRL+C;
预期输出:
received SIGINT, exiting....
真实输出:
received SIGINT, exiting....
received SIGINT, exiting....
received SIGINT, exiting....
为什么我会出现这种行为?
编辑:代码更新
这是当 1 个分叉完成并且孩子完成后我关闭服务器时发生的情况:
^C7518
7516
Received SIGINT, exiting...
Received SIGINT, exiting...
exit(0)
解决方案:问题是我在指令之后没有写do_child()
...代码更新了!