DisposeLocalCopyOfClientHandle

DisposeLocalCopyOfClientHandle

与匿名管道建立连接之后的步骤需要服务器调用DisposeLocalCopyOfClientHandle。 MSDN解释:

试图了解,为什么在关闭客户端时不通知服务器,我继续在引用源上查看DisposeLocalCopyOfClientHandle:

// This method is an annoying one but it has to exist at least until we make passing handles between
// processes first class.  We need this because once the child handle is inherited, the OS considers
// the parent and child's handles to be different.  Therefore, if a child closes its handle, our
// Read/Write methods won't throw because the OS will think that there is still a child handle around
// that can still Write/Read to/from the other end of the pipe.
//
// Ideally, we would want the Process class to close this handle after it has been inherited.  See
// the pipe spec future features section for more information.
//
// Right now, this is the best signal to set the anonymous pipe as connected; if this is called, we
// know the client has been passed the handle and so the connection is live.
[System.Security.SecurityCritical]
public void DisposeLocalCopyOfClientHandle() {
    if (m_clientHandle != null && !m_clientHandle.IsClosed) {
       m_clientHandle.Dispose();
    }
}
这句话使我感到困惑:

首先,父级的句柄和子级的句柄(即服务器的m_handle和服务器的m_clientHandle传递给 child )不是一样吗?这里的“不同”是指“引用不同的对象”(这是我理解的方式),还是具有其他含义?

最佳答案

您的困惑源于服务器和客户端也是父进程和子进程的事实。管道句柄是服务器或客户端,但可以存在于父项和子项中。有一小段时间,在服务器产生客户端之后但在调用DisposeLocalCopyOfClientHandle之前,三个句柄在起作用:

  • 服务器(父进程)中管道的服务器句柄。
  • 服务器(父)进程中管道的客户端句柄。
  • 在客户端(子进程)中,从父进程继承的管道的客户端句柄。

  • 在 child 启动并运行之后,需要关闭第二个句柄,因为正如注释所解释的,在所有客户端句柄都已关闭之前,管道一直可用。如果第二个 handle 卡住了,则将阻止服务器检测到子进程已完成。

    除了使用继承,该实现还可以生成子进程并使用 DuplicateHandle ,因为可以立即关闭原始句柄,因此无需使用此辅助方法。这大概是“在进程的第一类之间传递句柄”的意思。

    10-07 12:08