C# 使用匿名管道进行本地进程间通信

目录

写在前面

代码实现

客户端进程

服务端进程

调用示例


写在前面

相对于命名管道通讯方式而言,匿名管道开销更小,更轻松便捷;缺点就是无法进行网络通讯,只能在本机使用,应用场景相对狭窄;适合于本地多进程之间的通讯,比如主节点和多个从节点之间的交互。

以下代码实现主要来自微软官网,实现了采用匿名管道将字符串从父进程发送到子进程的功能。

代码实现

客户端进程

cs 复制代码
using System;
using System.IO;
using System.IO.Pipes;

class PipeClient
{
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            // 指定为接收端: PipeDirection.In 
            using PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, args[0]);
            Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.", pipeClient.TransmissionMode);

            using (StreamReader sr = new StreamReader(pipeClient))
            {
                // Display the read text to the console
                string temp;

                // Wait for 'sync message' from the server.
                do
                {
                    Console.WriteLine("[CLIENT] Wait for sync...");
                    temp = sr.ReadLine();
                }
                while (!temp.StartsWith("SYNC"));

                // Read the server data and echo to the console.
                while ((temp = sr.ReadLine()) != null)
                {
                    Console.WriteLine("[CLIENT] Echo: " + temp);
                }
            }
        }
        Console.Write("[CLIENT] Press Enter to continue...");
        Console.ReadLine();
    }
}

服务端进程

cs 复制代码
using System;
using System.IO;
using System.IO.Pipes;
using System.Diagnostics;

class PipeServer
{
    static void Main()
    {
        Process pipeClient = new Process();
        pipeClient.StartInfo.FileName = "pipeClient.exe";

        // 指定为发送端:PipeDirection.Out
        using AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
        Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", pipeServer.TransmissionMode);
        // Pass the client process a handle to the server.
        pipeClient.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
        pipeClient.StartInfo.UseShellExecute = false;
        pipeClient.Start();

        pipeServer.DisposeLocalCopyOfClientHandle();

        try
        {
            // Read user input and send that to the client process.
            using (StreamWriter sw = new StreamWriter(pipeServer))
            {
                sw.AutoFlush = true;
                // Send a 'sync message' and wait for client to receive it.
                sw.WriteLine("SYNC");
                pipeServer.WaitForPipeDrain();
                // Send the console input to the client process.
                Console.Write("[SERVER] Enter text: ");
                sw.WriteLine(Console.ReadLine());
            }
        }
        // Catch the IOException that is raised if the pipe is broken
        // or disconnected.
        catch (IOException e)
        {
            Console.WriteLine("[SERVER] Error: {0}", e.Message);
        }

        pipeClient.WaitForExit();
        pipeClient.Close();
        Console.WriteLine("[SERVER] Client quit. Server terminating.");
        
        Console.ReadLine();
    }
}

调用示例

需要注意的是除了客户端的exe和dll,配置文件PipeClient.runtimeconfig.json也需要一并放入服务端的运行目录。

相关推荐
向夏威夷 梦断明暄43 分钟前
C# 弃元模式:从语法糖到性能利器的深度解析
服务器·数据库·c#
小大宇1 小时前
python sqlalchemy 案例
开发语言·python
名字还没想好☜2 小时前
Go 结构体内存对齐:调整字段顺序,同样的字段省下 40% 内存
开发语言·后端·golang·go·内存对齐
玛丽莲茼蒿2 小时前
很难出错的Spring5(十)—— IOC进阶
java·开发语言·jvm
Ulyanov2 小时前
雷达导引头仿真中的坐标系——从惯性系到量测角
开发语言·python·算法·系统仿真·雷达信号处理·雷达导引头
rick9772 小时前
C# × Python 互操不再难:DotNetPy 让两大生态真正融合
c#
上海安当技术2 小时前
车间电脑指纹登录怎么做?从 FIDO2 公钥体系到统一身份认证的技术拆解
开发语言·电脑·php
前鼻音太阳熊2 小时前
【MES系统】- 工业HMI状态机可视化实践:从手写SVG到Cytoscape.js的技术选型与踩坑
开发语言·javascript·ecmascript
阿米亚波3 小时前
【C++ STL】std::array
java·开发语言·c++
wuyk5553 小时前
66.嵌入式C语言进阶:共用体(Union)实战指南——单片机内存省一半的神级技巧
c语言·开发语言·stm32·单片机·嵌入式硬件