When the fork process, file descriptors are duplicated in the child process. However, these file descriptors are different from each other. Closing the file descriptor in the child file does not affect the corresponding file descriptor in the parent object and vice versa.
In your case, since the child process needs the accepted new_sockfd socket, and the parent process continues to use the sockfd listening socket, the child should close(sockfd) (in your if block; this does not affect the parent), and the parent should close(new_sockfd) (in your else block, this does not affect the child). The fact that the parent and child functions works simultaneously does not affect this.
dbush
source share