Named Pipes: A Practical Example of Inter-Process Communication
Named pipes offer a robust and efficient solution for inter-process communication (IPC). This example uses a simple console application to demonstrate how two programs exchange messages via named pipes.
We'll build two programs: Program A, which sends a message, and Program B, which receives and responds.
Program A: Sending the Message
Program A uses the .NET Framework's NamedPipeClientStream
to connect to a named pipe called "PipeLine." After connecting, it transmits the message "Hello World" using a StreamWriter
.
Program B: Receiving and Responding
Program B employs NamedPipeServerStream
to create and monitor the "PipeLine" named pipe. Upon connection, a StreamReader
and StreamWriter
handle message reception and response.
<code class="language-csharp">// Program A using (var client = new NamedPipeClientStream("PipeLine")) { client.Connect(); using (var writer = new StreamWriter(client)) { writer.WriteLine("Hello World"); writer.Flush(); } } // Program B using (var server = new NamedPipeServerStream("PipeLine")) { server.WaitForConnection(); using (var reader = new StreamReader(server)) using (var writer = new StreamWriter(server)) { string message = reader.ReadLine(); writer.WriteLine("Roger That"); writer.Flush(); } }</code>
This illustrates the core principles of named pipe communication: pipe creation, connection establishment, and message exchange. This straightforward example provides a foundational understanding for implementing IPC solutions in your projects.
The above is the detailed content of How Can Named Pipes Facilitate Simple Inter-Process Communication?. For more information, please follow other related articles on the PHP Chinese website!