管道分为两种类型:

  • 匿名管道。

匿名管道可用于线程间通信,也可用于父进程和子进程之间的通信,因为管道句柄可以轻松传递给所创建的子进程。

AnonymousPipeClientStream 类来实现匿名管道。

In。

  下面的示例展示了服务器进程:

 1 using System;
 2 using System.IO;
 3 using System.IO.Pipes;
 4 using System.Diagnostics;
 5 
 6 class PipeServer
 7 {
 8     static void Main()
 9     {
10         Process pipeClient = new Process();
11 
12         pipeClient.StartInfo.FileName = "pipeClient.exe";
13 
14         using (AnonymousPipeServerStream pipeServer =
15             new AnonymousPipeServerStream(PipeDirection.Out,
16             HandleInheritability.Inheritable))
17         {
18             Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
19                 pipeServer.TransmissionMode);
20 
21             // Pass the client process a handle to the server.
22             pipeClient.StartInfo.Arguments =
23                 pipeServer.GetClientHandleAsString();
24             pipeClient.StartInfo.UseShellExecute = false;
25             pipeClient.Start();
26 
27             pipeServer.DisposeLocalCopyOfClientHandle();
28 
29             try
30             {
31                 // Read user input and send that to the client process.
32                 using (StreamWriter sw = new StreamWriter(pipeServer))
33                 {
34                     sw.AutoFlush = true;
35                     // Send a 'sync message' and wait for client to receive it.
36                     sw.WriteLine("SYNC");
37                     pipeServer.WaitForPipeDrain();
38                     // Send the console input to the client process.
39                     Console.Write("[SERVER] Enter text: ");
40                     sw.WriteLine(Console.ReadLine());
41                 }
42             }
43             // Catch the IOException that is raised if the pipe is broken
44             // or disconnected.
45             catch (IOException e)
46             {
47                 Console.WriteLine("[SERVER] Error: {0}", e.Message);
48             }
49         }
50 
51         pipeClient.WaitForExit();
52         pipeClient.Close();
53         Console.WriteLine("[SERVER] Client quit. Server terminating.");
54     }
55 }
View Code

相关文章:

  • 2021-05-31
  • 2021-10-06
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-17
  • 2022-01-01
  • 2022-01-05
  • 2021-07-22
  • 2021-08-07
  • 2022-12-23
相关资源
相似解决方案