Search code examples
csocketsfork

How to correctly use socket close for fork?


I have questions about how to correctly close the socket file descriptor. Let's assume the server forks another procedure whenever it accepts a new connection. The original socket file descriptor is sockfd and the new socket file descriptor is new_sockfd.

sockfd = socket(...)
bind(...);
listen(...);

while(1) {
  new_sockfd = accept(...);
  if(fork() == 0) {
    // Child process
    dosomething(...);

  }
  else {

  }
}

My question is, where we should put close(sockfd) and close(new_sockfd). I have seen some examples in the website (http://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm "Handle Multiple Connection") they put close(sockfd) inside the if block and close(new_sockfd) in the else block. But, after the fork, aren't the two processes running in parallel? If parent process closes the new_sockfd, won't it affect the child process to handle the socket? Also, if child process executes close(sockfd), won't this affect the entire socket program?


Solution

  • When a process forks, file descriptors are duplicated in the child process. However, these file descriptors are distinct from each other. Closing a file descriptor in the child doesn't affect the corresponding file descriptor in the parent, and vice versa.

    In your case, since the child process needs the accepted socket new_sockfd and the parent process continues to use the listening socket sockfd, the child should close(sockfd) (in your if block; this doesn't affect the parent) and the parent should close(new_sockfd) (in your else block; this doesn't affect the child). The fact that the parent and child are running at the same time doesn't affect this.