Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use socket close for fork?

Tags:

c

fork

sockets

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?

like image 645
Jes Avatar asked Jul 17 '15 03:07

Jes


People also ask

When should you close a socket?

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.

Which is the most optimal block to close the socket of a file?

To close the socket you should use socket. close() and I would recommend you not to rely on the destroy function.

How to close a socket in c#?

Close(Int32) Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.


1 Answers

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.

like image 57
dbush Avatar answered Oct 17 '22 00:10

dbush