I've implemented a little WCF Service in .net 3.5, on whom clients connect by TCP on port 4321. This service can spawn other processes (via System.Diagnostics.Process). Of course, when the service is killed or crashes or whatever, the spawned processes remain. The problem I have is If I try to restart the service while those processes still run, I get the following exception :
CommunicationException : There is already a listener on IP endpoint 0.0.0.0:4321. Make sure that you are not trying to use this end point multiple times in your application and that there are no other applications listening on this endpoint.
Indeed, when I run netstat, I can see that there's a process that listens onto port TCP 4321 :
TCP 0.0.0.0:4321 MTL-WKS-AG196:0 LISTENING 97308
The process ID that you see here (97308) is the one of the service I first started (which shouldn't exist anymore, as it was killed). The only way to free the port is to kill all processes that were spawned during the life of the service.
I don't know much about ports and processes but my understanding is that a child process "inherits" the ports listened by the parent process. Is it more or less what happens ?
Is there a way to cancel this behavior ? Without having access to the code of the spawned process ?
Also, I don't really think it's possible but is there a way to tell Windows to kill the child processes whenever their parent process is killed ?
Thanks !
In Linux,When we kill parent process then child process will become Orphan and child process is adopt by init process so then ppid of child process will 1. On UNIX, there is no enforced relation between parent and child process's lifetimes.
RETURN VALUE topOn success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set to indicate the error.
When either the parent or child changes the contents of memory, whomever did the change gets a private copy of the changed memory (changes don't get shared); the other process keeps the "old" copy for himself. If all they do is read, no additional memory is used.
Answer: Only the shared memory segments are shared between the parent process and the newly forked child process. Copies of the stack and the heap are made for the newly created process.
Apparently BCL allows all handles to be inheritted by the child process (the port in this case) See Stephen Cleary response on MSDN Forum
I'm currently having this similar problem and the using a temporary workaround this. I've enabled the Net.Tcp Port Sharing service and enabling it your wcf service app.config. (More info here)
Will be looking to implement Stephen's suggestions as a more permanent solution when I get the time :)
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