Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close opened sockets in child process

I have a SIP server (daemon) which is listening on tcp socket 5060. Now in this parent process I create a child process and do something in child. Now, What happens is when I close this tcp socket in parent process and try to create again (Lets say I am disabling and enabling SIP on this server), creating this socket gives me error. I have debugged this issue and found the root-cause. Root-cause is when child is created it inherits (gets a copy of) all the opened fd/sockets from parent. when parent closes the tcp socket it still opened in child (ref_counter!=0) and thus I cant open the socket again in parent!!

Now, the generic solution i want is - As soon as a child process is started it checks any opened fd (of type IPv4/TCP) and close them so that there is no side effect of this child process on parent. How can this be done in C-unix ? I have contemplated about doing in the direction of system(lsof | grep | awk) and get the file descriptors, but then how do i close them ? Any other solution to close the socket in child ? Is there a method where I can pass port number and it gives me already created fd ?

Solution which I dont want are (Which will not be helpful for me ) -
1. In parent process, initially while creating tcp socket with some flag so that they are not copied by child. (I can not modify that socket creation in parent)! 2. Passing file descriptor from parent to child at the time of creation of child process. I can not do that as I dont have that fd. The solution has to be something which needs to be put in child process!

Thanks

like image 601
Adam Avatar asked Dec 06 '25 20:12

Adam


2 Answers

You have the file descriptors. Just close the ones you don't need!

In the child you should close the listening socket.

In the parent you should close the accepted socket (=the new connection).

like image 84
Klas Lindbäck Avatar answered Dec 09 '25 10:12

Klas Lindbäck


Children inherit their parents' open file descriptors (this also includes sockets). In your case, the child process also has the socket open and bound to the port above. Thus, no other process (in normal case) can listen on this port anymore. What you need to do is to close the socket in the child (or, in case you don't need it before fork()) close it in the parent prior to forking.

like image 44
Alexander L. Belikoff Avatar answered Dec 09 '25 09:12

Alexander L. Belikoff