Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the socket descriptor closed by the function exit(exit code)?

Tags:

c

sockets

exit

I created a multi-process client-server in c-unix language. Every connection with a client is managed as a child process. When an error occurs, i simply call the function exit(EXIT_FAILURE), because i read that this function closes all open streams. The question is: do I have to close the client socket descriptor or closing is automatic?

an example of my code is:

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?
        }
like image 861
user1071138 Avatar asked Oct 09 '22 11:10

user1071138


1 Answers

You have to close the socket in the parent process as the descriptor is duplicated after the fork.

Calling exit() will close the socket in the child process automatically, as you already suspected.

The operating system has to release all resources of a process when it finishes, otherwise the systems resources would get used up by badly written programs.

like image 147
thumbmunkeys Avatar answered Oct 13 '22 11:10

thumbmunkeys