Named pipes provide a robust method for inter-process communication (IPC), enabling efficient data exchange between different programs. This example demonstrates a basic test application where one process sends a message and receives a reply.
The Python code uses the multiprocessing
module to create a sender and a receiver process.
Sender Process:
<code class="language-python">import multiprocessing def sender(): pipe_in, pipe_out = multiprocessing.Pipe() p = multiprocessing.Process(target=receiver, args=(pipe_in,)) p.start() pipe_out.send("Hello from Python") p.join() </code>
Receiver Process:
<code class="language-python">def receiver(pipe_in): message = pipe_in.recv() print(message) # Output: Hello from Python pipe_in.send("Acknowledged from Python")</code>
The C# code utilizes named pipe client and server streams for the IPC mechanism.
<code class="language-csharp">using System; using System.IO; using System.IO.Pipes; using System.Threading.Tasks; class Program { static void Main() { StartServer(); Task.Delay(1000).Wait(); // Allow server to start // Client using (var client = new NamedPipeClientStream("PipesOfPeace")) { client.Connect(); using (StreamWriter writer = new StreamWriter(client)) { writer.WriteLine("Hello from C#"); writer.Flush(); } using (StreamReader reader = new StreamReader(client)) { string response = reader.ReadLine(); // Reads "Acknowledged from C#" Console.WriteLine(response); } } } static void StartServer() { Task.Factory.StartNew(() => { using (var server = new NamedPipeServerStream("PipesOfPeace")) { server.WaitForConnection(); using (StreamReader reader = new StreamReader(server)) { string message = reader.ReadLine(); // Reads "Hello from C#" Console.WriteLine(message); } using (StreamWriter writer = new StreamWriter(server)) { writer.WriteLine("Acknowledged from C#"); writer.Flush(); } } }); } }</code>
Both examples demonstrate the basic principles of using named pipes for inter-process communication. A message is sent, received, and a response is sent back, illustrating a simple yet effective IPC solution.
The above is the detailed content of How Can Named Pipes Facilitate Interprocess Communication in Python and C#?. For more information, please follow other related articles on the PHP Chinese website!