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 !
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 :)
精彩评论