Process process = new Process(); process.StartInfo.FileName = "child.exe"; //创建匿名管道流实例, using (AnonymousPipeServerStream pipeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) { //将句柄传递给子进程 process.StartInfo.Arguments = pipeStream.GetClientHandleAsString(); process.StartInfo.UseShellExecute = false; process.Start(); //销毁子进程的客户端句柄? pipeStream.DisposeLocalCopyOfClientHandle(); using (StreamWriter sw = new StreamWriter(pipeStream)) { sw.AutoFlush = true; //向匿名管道中写入内容 sw.WriteLine(Console.ReadLine()); } } process.WaitForExit(); process.Close();
子进程声明了一个AnonymousPipeClientStream实例,并从此实例中读取内容,如下代码:
using (StreamReader sr = new StreamReader( new AnonymousPipeClientStream(PipeDirection.In, args[0]))) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine("Echo: {0}", line); } }这个程序要在cmd命令行中执行,否则看不到执行效果,执行的结果是在父进程中输入一行文本,子进程输出Echo:文本。
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("testpipe")) { pipeStream.WaitForConnection(); using (StreamWriter writer = new StreamWriter(pipeStream)) { writer.AutoFlush = true; string temp; while ((temp = Console.ReadLine()) != "stop") { writer.WriteLine(temp); } } }如下客户端进程代码:
static void Main(string[] args) { using (NamedPipeClientStream pipeStream = new NamedPipeClientStream("testpipe")) { pipeStream.Connect(); //在client读取server端写的数据 using (StreamReader rdr = new StreamReader(pipeStream)) { string temp; while ((temp = rdr.ReadLine()) != "stop") { Console.WriteLine("{0}:{1}",DateTime.Now,temp); } } } Console.Read(); }上面代码执行结果是服务端输入文本,客户端显示接受到文本的时间和文本内容。上面说了命名管道是全双工通信的,所以你也可以让客户端写内容,而服务端接受内容,代码大同小异。
static void Main(string[] args) { UTF8Encoding encoding = new UTF8Encoding(); string message1 = "Named Pipe Message Example."; string message2 = "Another Named Pipe Message Example."; Byte[] bytes; using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("messagepipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None)) { pipeStream.WaitForConnection(); // Let’s send two messages. bytes = encoding.GetBytes(message1); pipeStream.Write(bytes, 0, bytes.Length); bytes = encoding.GetBytes(message2); pipeStream.Write(bytes, 0, bytes.Length); } }客户端代码:
static void Main(string[] args) { Decoder decoder = Encoding.UTF8.GetDecoder(); Byte[] bytes = new Byte[10]; Char[] chars = new Char[10]; using (NamedPipeClientStream pipeStream = new NamedPipeClientStream("messagepipe")) { pipeStream.Connect(); pipeStream.ReadMode = PipeTransmissionMode.Message; int numBytes; do { string message = ""; do { numBytes = pipeStream.Read(bytes, 0, bytes.Length); int numChars = decoder.GetChars(bytes, 0, numBytes, chars, 0); message += new String(chars, 0, numChars); } while (!pipeStream.IsMessageComplete); decoder.Reset(); Console.WriteLine(message); } while (numBytes != 0); } }基于消息传递信息需要在构造NamedPipeServerStream时指定PipeTransmissionMode为PipeTransmissionMode.Message;而在客户端接收时也需指定NamedPipeClientStream的ReadMode属性为PipeTransmissionMode.Message