我用 c-unix 语言创建了一个多进程客户端 - 服务器。与客户端的每个连接都作为子进程进行管理。发生错误时,我只是调用函数 exit(EXIT_FAILURE),因为我读到该函数会关闭所有打开的流。问题是:我必须关闭客户端套接字描述符还是自动关闭?
我的代码的一个例子是:
while(1){
if((client_sock=accept(ds_sock,&client,&s_client))==-1){
printf("Accept error\n");
exit(EXIT_FAILURE);
}
if(fork()==0){ //child
if((close(ds_sock)==-1)){
printf("Closing error\n");
exit(EXIT_FAILURE);
}
if((read(client_sock,&up,sizeof(userpass)))==-1){
printf("Error read\n");
exit(EXIT_FAILURE); //Does this instruction close the client_sock too?
}
Run Code Online (Sandbox Code Playgroud)
您必须关闭父进程中的套接字,因为描述符在分叉后会重复。
正如您已经怀疑的那样,调用 exit() 将自动关闭子进程中的套接字。
操作系统必须在进程完成时释放该进程的所有资源,否则系统资源将被编写得不好的程序耗尽。