Link to home
Create AccountLog in
Avatar of DineshJolania
DineshJolania

asked on

Why do we ned to close listen socket in child process in a concurrent server ?

Hi Experts,
My question is " What happens  if we don't close listen socketin child process?. It is mandatory ?
Generally we write in  following manner.
bind(listensock, (struct sockaddr *) &sAddr, sizeof(sAddr));
Afterward, we put the socket into listening mode to listen for incoming connections.
    listen(listensock, 5);
We then call accept() and allow it to block waiting for connection requests from
 clients. After accept returns, we call fork() to create a new process. If it returns 0, then we are in the child process; otherwise, the PID of the new child is returned.
     while (1) {
      newsock = accept(listensock, NULL, NULL);
      if ((pid = fork()) = = 0) {
     printf("%s\n", buffer);
Once in the child process, we close the listening socket.
We know  that all descriptors are copied from the parent process to the child.
The child process does not need the listening socket any longer, so we close the
child's reference on that socket.
     close(listensock);
     nread = recv(newsock, buffer, 25, 0);
     buffer[nread] = '\0';
     send(newsock, buffer, nread, 0);
     close(newsock);
     exit(0);
    }


ASKER CERTIFIED SOLUTION
Avatar of ravenpl
ravenpl
Flag of Poland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of DineshJolania
DineshJolania

ASKER

Thanks  a lot ravenpl. I carried this confusion for years.