Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket doesn't close after application exits if a launched process is open

Tags:

c#

.net

sockets

My C# .net application currently does the following (among other things):

  1. Creates a thread which opens a socket on a specific port and waits for an instruction.
  2. Message comes in, socket thread reads the message and raises an event.
  3. An event handler calls the necessary functions to parse the message and performs the necessary action, for instance, launching an application.
  4. The specified external "application" launches, asynchronously.

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?

like image 203
JSideris Avatar asked Apr 19 '12 19:04

JSideris


People also ask

What can happen if you do not close a socket when you finish using it?

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.

What happens when an application opens a socket?

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.


2 Answers

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.

like image 143
Josh Avatar answered Oct 04 '22 16:10

Josh


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.

like image 26
Aaron Anodide Avatar answered Oct 04 '22 18:10

Aaron Anodide