我正在尝试从 .Net 调用 FastCGI 应用程序 - 这意味着我需要将句柄传递给子进程的套接字。
但是我看到的是,如果我使用该STARTF_USESTDHANDLES
标志,CreateProcess()
则子应用程序在尝试从套接字读取时会失败。
我已经通过不指定来解决这个问题STARTF_USESTDHANDLES
,但我想了解为什么会发生这种情况。,特别是因为我对 MSDN 文档的理解是我应该在重定向标准输入时使用这个标志。
这是我的 C# 应用程序(错误检查等...为简洁起见已删除)
string command = @"FastCGI.exe";
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 8221));
// Duplicate the socket handle so that it is inheritable
SafeFileHandle childHandle;
NativeMethods.DuplicateHandle(NativeMethods.GetCurrentProcess(), new SafeFileHandle(listener.Handle, false), NativeMethods.GetCurrentProcess(), out childHandle, 0, true, NativeMethods.DUPLICATE_SAME_ACCESS);
NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO();
startupInfo.hStdInput = childHandle;
// Uncommenting the following line causes the problem
//startupInfo.dwFlags = NativeMethods.STARTF_USESTDHANDLES;
// Start the child process
NativeMethods.PROCESS_INFORMATION processInformation;
NativeMethods.CreateProcess(null, command, null, null, true, 0, IntPtr.Zero, null, startupInfo, out processInformation);
// To prevent the process closing the socket handle
Console.ReadKey();
我的子进程是包含在Windows Azure VS2010 C# 代码示例中的示例 FastCGI 应用程序,失败的行是:
BOOL ret = ReadFile( hStdin, pBuffer, dwSize, &nNumberOfBytes, NULL );
if(!ret)
{
// dw = 87 (ERROR_INVALID_PARAMETER)
DWORD dw = GetLastError();
}
我对套接字和句柄编程都比较陌生,所以任何关于为什么会发生这种情况的见解都将不胜感激。