Tra*_*acy 2 sockets process parent-child
我被这个模拟服务器 - 客户端交互的代码片段所困,假设sockfd是在服务器端创建的套接字文件描述符.
我的问题是当父和它的子进程'同时'运行时,并且在子进程执行时间片期间,它关闭服务器套接字sockfd,然后当执行流到第二次循环,调用accpet函数时,参数sockfd有效,是否被子进程关闭,即从内核文件描述符表中解除分配?
while (1) {
//accept a connection from client,get the new socket from client
//is the sockfd valid here,is it closed by the child in
//the previous loop
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork();
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(sockfd); // can't this cause problem ??
dostuff(newsockfd);
exit(0);
}
else close(newsockfd);
} /* end of while */
Run Code Online (Sandbox Code Playgroud)
在这段代码中:
if (pid == 0) {
close(sockfd); // can't this cause problem ??
dostuff(newsockfd);
exit(0);
}
Run Code Online (Sandbox Code Playgroud)
该close()只影响孩子的一份sockfd文件描述.
父进程的副本仍然在下一次循环时打开使用.
子进程被认为是关闭不需要的继承文件描述符的良好方式.