我正在学习网络编程并尝试实现一个HTTP服务器。我正在遵循 C 套接字编程指南(https://beej.us/guide/bgnet/html/split/client-server-background.html)并遇到了这个示例:
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
if (send(new_fd, "Hello, world!", 13, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
我感到困惑的部分是进程的分叉。
当原始套接字文件描述符(sockfd)仅在原始父进程中创建时,为什么我们要关闭它?或者更一般地说,父进程创建的所有资源是否都会在子进程中复制 - 例如套接字文件?