c - How to correctly use socket close for fork? -
i have questions how correctly close socket file descriptor. let's assume server forks procedure whenever accepts new connection. original socket file descriptor sockfd
, new socket file descriptor new_sockfd
.
sockfd = socket(...) bind(...); listen(...); while(1) { new_sockfd = accept(...); if(fork() == 0) { // child process dosomething(...); } else { } }
my question is, should put close(sockfd)
, close(new_sockfd)
. have seen examples in website (http://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm "handle multiple connection") put close(sockfd)
inside if
block , close(new_sockfd)
in else
block. but, after fork, aren't 2 processes running in parallel? if parent process closes new_sockfd
, won't affect child process handle socket? also, if child process executes close(sockfd)
, won't affect entire socket program?
when process forks, file descriptors duplicated in child process. however, these file descriptors distinct each other. closing file descriptor in child doesn't affect corresponding file descriptor in parent, , vice versa.
in case, since child process needs accepted socket new_sockfd
, parent process continues use listening socket sockfd
, child should close(sockfd)
(in if
block; doesn't affect parent) , parent should close(new_sockfd)
(in else
block; doesn't affect child). fact parent , child running @ same time doesn't affect this.
Comments
Post a Comment