I am writing a program calls “APPLICATION A” for the sake of simplicity which opens a socket connection to port 8881 on local host; later it spawns an exe application call “APPLICATION B” using the code blow:
try
{
XmSam.Log("Spawning (" + process + ")");
ProcessEx proc = new ProcessEx();
proc.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + process + ".exe";
proc.StartInfo.Arguments = parameters;
proc.StartInfo.UseShellExecute = false;
proc.Start();
Program.Processes.Add(proc);
XmSam.Log("Spawned " + proc.ProcessName);
}
catch (Exception ex)
{
XmSam.Log(ex);
}
When I turn off APPLICATION A (either by stop the application or kill its process in window task manager), the APPLICATION B still runs which is fine. However, when I started APPLICATION A again I got the exception:
2012-10-18 16:21:23 - Only one usage of each socket address (protocol/network address/port) is normally permitted
2012-10-18 16:21:23 - at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
This error occured when APPLICATION A tried to open the socket to port 8881. This error would go away if I kill APPLICATION B. I don’t think it is because of APPLICATION B code because it has nothing such as the below code shows:
[STAThread]
static void Main()
{
while (true)
{
}
}
I tried to look at MSDN under Process class but I did not see anything about this. I assumed when you spawned a process, that process is independent to the invocation application but apparently that is not the case. Do you know of any setting that let me spawn a process without having it holding onto the invocation application?
I know another way is to have code in APPLICATION A to kill APPLICATION B but that is not the idea solution especially in the case of APPLICATION A crashes unexpectedly.
Thank you.
I found the answer after more digging around. I find this excellent article
In it, the main explanation for this issue is as follow:
So with that in mind, all I have to do is to update my UseShellExecute flag to true.