Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 592
  • Last Modified:

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);
    }


0
DineshJolania
Asked:
DineshJolania
1 Solution
 
ravenplCommented:
> After accept returns, we call fork() to create a new process.
fork may return -1 as well, which is error (no resources)

> The child process does not need the listening socket any longer, so we close the child's reference on that socket.
And the father sould close the accepted socket as well.

> My question is " What happens  if we don't close listen socketin child process?. It is mandatory ?
Well, if You will not use it, nothing wrong should happen, but close to avoid errors and confusions.

It's like - neverthless the system will close all sockets and free all memory(except shared one), you should do it by Yourself before exit - right?
0
 
DineshJolaniaAuthor Commented:
Thanks  a lot ravenpl. I carried this confusion for years.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now