如何将SOCKET(HANDLE)从非托管C程序传递到.NET子进程?

时间:2018-10-29 15:15:01

标签: c .net sockets handle

我们有一个用C编写的Windows服务(WS)。WS在端口上侦听传入的请求。请求之一是启动子进程并将SOCKET传递给子进程,以便请求应用程序服务器(RAS)之后继续与子进程进行对话。子进程可执行文件(CPE)也是用C编写的。

这是WS的(简化)代码:

... 
HANDLE curr_channel // is the SOCKET our WS got from accepting an incoming connection attempt
HANDLE process_h = GetCurrentProcess();
HANDLE new_channel;
DuplicateHandle(process_h, curr_channel, process_h, &new_channel, 0, TRUE, DUPLICATE_SAME_ACCESS); // note that bInheritHandles is set to TRUE (1)
char command_line[2048];
sprintf(command_line, "<path to executable to be started as child process> %Iu", (unsigned __int64)new_channel);
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof(PROCESS_INFORMATION));
STARTUPINFO startup;
memset(&startup, 0, sizeof(STARTUPINFO));
startup.cb = sizeof(STARTUPINFO);
CreateProcess(NULL, command_line, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process_info); // note that bInheritHandles is set to TRUE (1)
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
CloseHandle(new_channel);
...

这是CPE的(简化)代码:

...
int pipeFd = atoi(argv[1]);
char *outBuf = ... // the message to be sent to the RAS as this is waiting for a (synchronous) response
int size = ... // length of this message
int cnt = send(pipeFd, outBuf, size, 0);
...

多年来,这一切一直像魅力一样运作。现在,我们想用C#编写的程序替换CPE,我们称其为CPE.NET。 WS应该保持原样(用C编写)。

这是CPE.NET的(简体)代码:

class Program {

    [DllImport("ws2_32.dll")]
    extern static int send([In] IntPtr socketHandle, [In] IntPtr buffer, [In] int count, [In] SocketFlags socketFlags);

    public static int Send(IntPtr socketHandle, byte[] buffer, int offset, int size, SocketFlags socketFlags) {
        unsafe {
            fixed (byte* pData = buffer) {
                return send(socketHandle, new IntPtr(pData + offset), size, socketFlags);
            }
        }
    }

    static void Main(string[] args) {
        int socketHandle;
        if (!int.TryParse(args[1], out socketHandle))
            return;
        byte[] data = new byte[] { ... }; // the message to be sent to the RAS as this is waiting for a (synchronous) response
        int retSendWithDotNet = Send(new IntPtr(socketHandle), data, 0, data.Length, 0);
        ...

现在的问题是retSendWithDotNet始终为-1。知道为什么会这样吗?

谢谢, 迈克尔

1 个答案:

答案 0 :(得分:0)

“您需要调用WSAGetLastError以获得更多信息。我的猜测是套接字尚未初始化(请参阅WSAStartup)。”

简单但有效。调用WSAStartup()可以解决问题。 非常感谢。