How to use the plug connector?

I have questions about how to properly close a socket file descriptor. Suppose the server deploys a different procedure whenever it accepts a new connection. The initial 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 should we put close(sockfd) and close(new_sockfd) . I saw some examples on the website ( http://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm Handling Multiple Connections), they put close(sockfd) inside the if block and close(new_sockfd) in else . But, after the plug, do not two processes work in parallel? If the parent process closes new_sockfd , does it affect the child process to handle the socket? Also, if the child process executes close(sockfd) , will this not affect the entire socket program?

+7
c sockets
source share
2 answers

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.

+11
source share

The parent must close the accepted socket (in the else block): it remains open in the child process until the child is executed with it, and at that moment it must close its closure.

+2
source share

All Articles