跨进程连接匿名管道会产生无效的句柄错误,我正在使用System.Io.Pipes

时间:2012-02-17 17:48:12

标签: c# ipc

我正在尝试组建一个类来处理使用System.Io.Pipes提供的匿名管道的进程之间的Ipc。

我遇到的问题是,当我使用单个进程测试类时,管道设置正确,我可以在客户端和服务器之间发送数据而不会出现问题。但是,当我将客户端和服务器拆分为单独的进程(在同一台机器上)时,客户端无法连接到服务器管道的末尾。

调用时出现错误 System.Io.Exception无效的管道句柄

_outboundPipeServerStream = new AnonymousPipeClientStream(PipeDirection.Out, serverHandle);

该类的完整代码粘贴在下面。

基本上它的工作就像这样;

  1. 服务器进程。为入站数据创建匿名管道集 - 调用此管道A
  2. 服务器进程。启动客户端进程并通过命令参数
  3. 传递PipeHandle
  4. 客户流程。连接到管道A的末端
  5. 客户流程。为入站数据创建匿名管道集(管道B) 5客户流程。使用管道A将管道句柄传递回服务器
  6. 服务器进程。连接到管道B的末端
  7. 所以现在我们有两个匿名管道,指向服务器和客户端之间相反的方向。

    这是我的IPC课程的完整代码

        public class MessageReceivedEventArgs : EventArgs
    {
        public string Message { get; set; }
    }
    
    public class IpcChannel : IDisposable
    {
        private AnonymousPipeServerStream _inboundPipeServerStream;
        private StreamReader _inboundMessageReader;
        private string _inboundPipeHandle;
    
        private AnonymousPipeClientStream _outboundPipeServerStream;
        private StreamWriter _outboundMessageWriter;
    
        public delegate void MessageReceivedHandler(object sender, MessageReceivedEventArgs e);
        public event MessageReceivedHandler MessageReceived;
    
        private Thread _clientListenerThread;
        private bool _disposing = false;
    
        public IpcChannel()
        {
            SetupServerChannel();
        }
    
        public IpcChannel(string serverHandle)
        {
            SetupServerChannel();
            // this is the client end of the connection
    
            // create an outbound connection to the server
            System.Diagnostics.Trace.TraceInformation("Connecting client stream to server : {0}", serverHandle);
            SetupClientChannel(serverHandle);
    
            IntroduceToServer();
        }
    
        private void SetupClientChannel(string serverHandle)
        {
            _outboundPipeServerStream = new AnonymousPipeClientStream(PipeDirection.Out, serverHandle);
            _outboundMessageWriter = new StreamWriter(_outboundPipeServerStream)
            {
                AutoFlush = true
            };
        }
    
        private void SetupServerChannel()
        {
            _inboundPipeServerStream = new AnonymousPipeServerStream(PipeDirection.In);
            _inboundMessageReader = new StreamReader(_inboundPipeServerStream);
            _inboundPipeHandle = _inboundPipeServerStream.GetClientHandleAsString();
            _inboundPipeServerStream.DisposeLocalCopyOfClientHandle();
    
            System.Diagnostics.Trace.TraceInformation("Created server stream " + _inboundPipeServerStream.GetClientHandleAsString());
    
            _clientListenerThread = new Thread(ClientListener)
            {
                IsBackground = true
            };
    
            _clientListenerThread.Start();
    
        }
    
        public void SendMessage(string message)
        {
            System.Diagnostics.Trace.TraceInformation("Sending message {0} chars", message.Length);
    
            _outboundMessageWriter.WriteLine("M" + message);
        }
    
        private void IntroduceToServer()
        {
            System.Diagnostics.Trace.TraceInformation("Telling server callback channel is : " + _inboundPipeServerStream.GetClientHandleAsString());
    
            _outboundMessageWriter.WriteLine("CI" + _inboundPipeServerStream.GetClientHandleAsString());
        }
    
        public string ServerHandle
        {
            get
            {
                return _inboundPipeHandle;
            }
        }
    
        private void ProcessControlMessage(string message)
        {
            if (message.StartsWith("CI"))
            {
                ConnectResponseChannel(message.Substring(2));
            }
        }
    
        private void ConnectResponseChannel(string channelHandle)
        {
            System.Diagnostics.Trace.TraceInformation("Connecting response (OUT) channel to : {0}", channelHandle);
    
            _outboundPipeServerStream = new AnonymousPipeClientStream(PipeDirection.Out, channelHandle);
            _outboundMessageWriter = new StreamWriter(_outboundPipeServerStream);
            _outboundMessageWriter.AutoFlush = true;
        }
    
        private void ClientListener()
        {
            System.Diagnostics.Trace.TraceInformation("ClientListener started on thread {0}", Thread.CurrentThread.ManagedThreadId);
    
            try
            {
                while (!_disposing)
                {
                    var message = _inboundMessageReader.ReadLine();
                    if (message != null)
                    {
                        if (message.StartsWith("C"))
                        {
                            ProcessControlMessage(message);
                        }
                        else if (MessageReceived != null)
                            MessageReceived(this, new MessageReceivedEventArgs()
                            {
                                Message = message.Substring(1)
                            });
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            finally
            {
    
            }
        }
    
        public void Dispose()
        {
            _disposing = true;
    
            _clientListenerThread.Abort();
    
            _outboundMessageWriter.Flush();
            _outboundMessageWriter.Close();
            _outboundPipeServerStream.Close();
            _outboundPipeServerStream.Dispose();
    
            _inboundMessageReader.Close();
            _inboundMessageReader.Dispose();
    
            _inboundPipeServerStream.DisposeLocalCopyOfClientHandle();
            _inboundPipeServerStream.Close();
            _inboundPipeServerStream.Dispose();
        }
    }
    

    在一个过程中,它可以像这样使用;

    class Program
    {
        private static IpcChannel _server;
        private static IpcChannel _client;
    
        static void Main(string[] args)
        {
            _server = new IpcChannel();
            _server.MessageReceived += (s, e) => Console.WriteLine("Server Received : " + e.Message);
    
            _client = new IpcChannel(_server.ServerHandle);
            _client.MessageReceived += (s, e) => Console.WriteLine("Client Received : " + e.Message);
    
    
            Console.ReadLine();
    
            _server.SendMessage("This is the server sending to the client");
    
            Console.ReadLine();
    
            _client.SendMessage("This is the client sending to the server");
    
            Console.ReadLine();
    
            _client.Dispose();
            _server.Dispose();
        }
    

    提前感谢任何建议。

2 个答案:

答案 0 :(得分:3)

您没有发布服务器代码,但无论如何。在服务器中:

  • 您需要指定客户端的管道句柄在创建时是可继承的。
  • 启动客户端时,需要指定继承可继承的句柄。

如果您错过了其中任何一个步骤,那么管道句柄在客户端进程中将无效。

此外,您的第4步将无效。如果在客户端中创建管道句柄,则在将其传回时对服务器没有任何意义。您可以使用DuplicateHandle函数完成此工作,但 更容易创建服务器中的所有句柄并在客户端中继承它们。

关键是句柄是按进程处理的,而不是系统范围的。

答案 1 :(得分:3)

启动子进程不要忘记设置 UseShellExecute = false ,否则不会继承句柄。