My C# .net application currently does the following (among other things):
When my application restarts, but the external application does not close, the socket doesn't seem to ever close. Then when I try to start up communication on that port again I get an error. However, as soon as I close the external application I am able to open a socket on that port.
It seems like my program is not closing down properly. It should be killing the socket when it exits, however when the external process is running that socket never closes.
Any ideas?
One way or another, if you don't close a socket, your program will leak a file descriptor. Programs can usually only open a limited number of file descriptors, so if this happens a lot, it may turn into a problem.
The socket() API creates an endpoint for communications and returns a socket descriptor that represents the endpoint. When an application has a socket descriptor, it can bind a unique name to the socket. Servers must bind a name to be accessible from the network.
This is just a stab because I have seen how you're starting the external process. If you're creating a Process object, my guess is you're not setting:
ProcessStartInfo.UseShellExecute = true;
If UseShellExecute is set to false, the child process will inherit open socket handles from the parent process. This will keep your socket open even if the parent application is closed.
From what I found here my suspicion might be confirmed that this is a case of the new process inheriting handles from the parent, thus causing your issue.
It looks like you can just copy/paste the code from that link to do a direct call to the Windows CreateProcess API with the flag set so as to not inherit handles.
Another separate idea is to write an intermediate launcher program that takes the command line information and then launches and then quits. This extra indirection might get you where you need to be with very little effort.
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