gpt4 book ai didi

c - 带 c 的 socket 和 fork

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:40 25 4
gpt4 key购买 nike

这里有一段我​​的 fork-server 代码:

    signal (SIGINT, ( void *)sig_handler);
while(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);
}
else{
attended_pid = waitpid(child_pid, NULL, 0);
if(attended_pid != child_pid){
printf("Child error");
}
}
}

我的问题是:我必须在执行客户端之前关闭主 sock (sockd) 吗?
我认为不是,但是:

  • 我添加了一个“sigint Controller ”,如果我在服务器上按 CTRL-C(带有注释的 sockd -> //close(sockd);),sigint 将在 2 个并发连接下执行 3 次(为什么??)<
  • 如果我有这个代码close(sockd) sigint 将只执行 1 次,但我得到一个 :bad file descriptoraccept 上指导。

那么,我该怎么办?
谢谢!

PS:我的签名代码:

void sig_handler(const int signo, const int sockd, const int newsockd){
if (signo == SIGINT){
printf("Ricevuto SIGINT, esco...\n");
if(newsockd) close(newsockd);
if(sockd) close(sockd);
exit(EXIT_SUCCESS);
}
}

最佳答案

来自fork(2)手册页:

The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).

这告诉我您不应该关闭子进程中的监听套接字。您也不应在父进程中关闭已接受的套接字,而应在完成后让子进程将其关闭。

关于c - 带 c 的 socket 和 fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12276619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com