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?
If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed. The descriptor of the socket to be closed. Note: All sockets should be closed before the end of your process.
To close the socket you should use socket. close() and I would recommend you not to rely on the destroy function.
Close(Int32) Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With