问题
I currently have a .NET program initiating a connection to a server and starting another, unmanaged executable. The native process should take over the same socket (it is essential for the connection not to be closed until the termination of the child process!) and start communicating through it with the server.
The aforementioned programs run both on Windows, however I'd prefer a solution that does not involve P/Invoke for the .NET part. As a side note, communication from parent to child process is not an issue so I can easily share data between the two.
Furthermore, once I start using the socket from the native process I don't need to use it from the .NET process anymore and the .NET process will terminate before I'm done using the socket from the unmanaged process, thus along with the solution I need to know what to do with the Socket object in .NET so that its disposal doesn't affect the OS socket and its usability.
Thanks in advance!
回答1:
.NET 2.0 and later offers handy method DuplicateAndClose.
Upd: looks like a hack will be needed to find out where (at which offset) in SocketInformation.ProtocolInformation the destination socket is stored. This can be done by capturing the byte array in the source process, then re-creating a socket in another .NET process and getting the socket handle there (in that second process). Then look where the data is in the byte array.
Also there's a good unmanaged way to duplicate sockets, described here.
回答2:
I think socket handles created by the .NET Socket class are inheritable by default. IIRC If you spawn the child process using Process.Start
and ProcessStartInfo.UseShellExecute = false
(ShellExecute doesn't allow handle inheritance), your child process should already inherit the socket handle. Did you try simply passing the Socket.Handle to the child process and using it there? And I think that as long as the child process owns the inherited handle, the socket remains open, even after the process that created it is gone. (I never used this directly, but I once had a mean bug that resulted from this behavior.) However, the socket might have been opened with flags like FILE_FLAG_OVERLAPPED etc. and you'll have to use the right combination of functions access it.
来源:https://stackoverflow.com/questions/4604273/pass-socket-handle-from-net-to-unmanaged-child-process