5

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?
        }
Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
user1071138
  • 656
  • 3
  • 12
  • 30
  • The subject of getting a socket closed "correctly" is rich with gotchas. Just one random example: https://stackoverflow.com/questions/12730477/close-is-not-closing-socket-properly – Ron Burk Oct 04 '20 at 02:13

1 Answers1

4

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.

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110