user1071138
user1071138

Reputation: 666

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

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?
        }

Upvotes: 6

Views: 4486

Answers (1)

thumbmunkeys
thumbmunkeys

Reputation: 20764

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.

Upvotes: 5

Related Questions