【微软技术栈】C#.NET 中的管道操作
C#.NET 管道为进程间通信提供了平台。 管道分为两种类型:
-
匿名管道。
匿名管道在本地计算机上提供进程间通信。 与命名管道相比,虽然匿名管道需要的开销更少,但提供的服务有限。 匿名管道是单向的,不能通过网络使用。 仅支持一个服务器实例。 匿名管道可用于线程间通信,也可用于父进程和子进程之间的通信,因为管道句柄可以轻松传递给所创建的子进程。在 .NET 中,可通过使用 AnonymousPipeServerStream 和 AnonymousPipeClientStream 类来实现匿名管道。
-
命名管道。
命名管道在管道服务器和一个或多个管道客户端之间提供进程间通信。 命名管道可以是单向的,也可以是双向的。 它们支持基于消息的通信,并允许多个客户端使用相同的管道名称同时连接到服务器进程。 命名管道还支持模拟,这样连接进程就可以在远程服务器上使用自己的权限。在 .NET 中,可通过使用 NamedPipeServerStream 和 NamedPipeClientStream 类来实现命名管道。
1、如何:使用匿名管道进行本地进程间通信
匿名管道在本地计算机上提供进程间通信。 它们提供的功能比命名管道少,但所需要的系统开销也少。 使用匿名管道,可以在本地计算机上更轻松地进行进程间通信。 不能使用匿名管道进行网络通信。
若要实现匿名管道,请使用 AnonymousPipeServerStream 和 AnonymousPipeClientStream 类。
1.1 示例 1
下面的示例展示了如何使用匿名管道将字符串从父进程发送到子进程。 本示例在父进程中创建一个 AnonymousPipeServerStream 对象,其 PipeDirection 值为 Out。然后,父进程通过使用客户端句柄创建 AnonymousPipeClientStream 对象来创建子进程。 子进程的 PipeDirection 值为 In。
接下来,父进程将用户提供的字符串发送给子进程。 字符串在子进程的控制台中显示。
下面的示例展示了服务器进程。
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";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.");}
}
1.2 示例 2
下面的示例展示了客户端进程。 服务器进程启动客户端进程,并为此进程提供客户端句柄。 客户端代码生成的可执行文件应命名为 pipeClient.exe
,并在运行服务器进程前复制到服务器可执行文件所在的相同目录中。
using System;
using System.IO;
using System.IO.Pipes;class PipeClient
{static void Main(string[] args){if (args.Length > 0){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 consolestring 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();}
}
2、如何:使用命名管道进行网络进程间通信
命名管道在管道服务器和一个或多个管道客户端之间提供进程间通信。 它们比匿名管道(用于在本地计算机上提供进程间的通信)提供更多的功能。 命名管道支持跨网络和多个服务器实例的全双工通信、基于消息的通信以及客户端模拟,这样连接进程便可在远程服务器上使用自己的权限集。若要实现名称管道,请使用 NamedPipeServerStream 和 NamedPipeClientStream 类。
2.1 示例 1
下面的示例展示了如何使用 NamedPipeServerStream 类创建命名管道。 在此示例中,服务器进程创建四个线程。 每个线程都可以接受客户端连接。 然后,连接的客户端进程向服务器提供文件名。 如果客户端拥有足够的权限,服务器进程就会打开文件,并将它的内容发送回客户端。
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;public class PipeServer
{private static int numThreads = 4;public static void Main(){int i;Thread?[] servers = new Thread[numThreads];Console.WriteLine("\n*** Named pipe server stream with impersonation example ***\n");Console.WriteLine("Waiting for client connect...\n");for (i = 0; i < numThreads; i++){servers[i] = new Thread(ServerThread);servers[i]?.Start();}Thread.Sleep(250);while (i > 0){for (int j = 0; j < numThreads; j++){if (servers[j] != null){if (servers[j]!.Join(250)){Console.WriteLine("Server thread[{0}] finished.", servers[j]!.ManagedThreadId);servers[j] = null;i--; // decrement the thread watch count}}}}Console.WriteLine("\nServer threads exhausted, exiting.");}private static void ServerThread(object? data){NamedPipeServerStream pipeServer =new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);int threadId = Thread.CurrentThread.ManagedThreadId;// Wait for a client to connectpipeServer.WaitForConnection();Console.WriteLine("Client connected on thread[{0}].", threadId);try{// Read the request from the client. Once the client has// written to the pipe its security token will be available.StreamString ss = new StreamString(pipeServer);// Verify our identity to the connected client using a// string that the client anticipates.ss.WriteString("I am the one true server!");string filename = ss.ReadString();// Read in the contents of the file while impersonating the client.ReadFileToStream fileReader = new ReadFileToStream(ss, filename);// Display the name of the user we are impersonating.Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",filename, threadId, pipeServer.GetImpersonationUserName());pipeServer.RunAsClient(fileReader.Start);}// Catch the IOException that is raised if the pipe is broken// or disconnected.catch (IOException e){Console.WriteLine("ERROR: {0}", e.Message);}pipeServer.Close();}
}// Defines the data protocol for reading and writing strings on our stream
public class StreamString
{private Stream ioStream;private UnicodeEncoding streamEncoding;public StreamString(Stream ioStream){this.ioStream = ioStream;streamEncoding = new UnicodeEncoding();}public string ReadString(){int len = 0;len = ioStream.ReadByte() * 256;len += ioStream.ReadByte();byte[] inBuffer = new byte[len];ioStream.Read(inBuffer, 0, len);return streamEncoding.GetString(inBuffer);}public int WriteString(string outString){byte[] outBuffer = streamEncoding.GetBytes(outString);int len = outBuffer.Length;if (len > UInt16.MaxValue){len = (int)UInt16.MaxValue;}ioStream.WriteByte((byte)(len / 256));ioStream.WriteByte((byte)(len & 255));ioStream.Write(outBuffer, 0, len);ioStream.Flush();return outBuffer.Length + 2;}
}// Contains the method executed in the context of the impersonated user
public class ReadFileToStream
{private string fn;private StreamString ss;public ReadFileToStream(StreamString str, string filename){fn = filename;ss = str;}public void Start(){string contents = File.ReadAllText(fn);ss.WriteString(contents);}
}
2.2 示例 2
下面的示例展示了使用 NamedPipeClientStream 类的客户端进程。 客户端连接到服务器进程,并将文件名发送到服务器。 因为此示例使用模拟,所以运行客户端应用的标识必须有权访问文件。 然后,服务器将文件内容发送回客户端。 接下来,文件内容在控制台中显示。
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
using System.Text;
using System.Threading;public class PipeClient
{private static int numClients = 4;public static void Main(string[] args){if (args.Length > 0){if (args[0] == "spawnclient"){var pipeClient =new NamedPipeClientStream(".", "testpipe",PipeDirection.InOut, PipeOptions.None,TokenImpersonationLevel.Impersonation);Console.WriteLine("Connecting to server...\n");pipeClient.Connect();var ss = new StreamString(pipeClient);// Validate the server's signature string.if (ss.ReadString() == "I am the one true server!"){// The client security token is sent with the first write.// Send the name of the file whose contents are returned// by the server.ss.WriteString("c:\\textfile.txt");// Print the file to the screen.Console.Write(ss.ReadString());}else{Console.WriteLine("Server could not be verified.");}pipeClient.Close();// Give the client process some time to display results before exiting.Thread.Sleep(4000);}}else{Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n");StartClients();}}// Helper function to create pipe client processesprivate static void StartClients(){string currentProcessName = Environment.CommandLine;// Remove extra characters when launched from Visual StudiocurrentProcessName = currentProcessName.Trim('"', ' ');currentProcessName = Path.ChangeExtension(currentProcessName, ".exe");Process?[] plist = new Process?[numClients];Console.WriteLine("Spawning client processes...\n");if (currentProcessName.Contains(Environment.CurrentDirectory)){currentProcessName = currentProcessName.Replace(Environment.CurrentDirectory, String.Empty);}// Remove extra characters when launched from Visual StudiocurrentProcessName = currentProcessName.Replace("\\", String.Empty);currentProcessName = currentProcessName.Replace("\"", String.Empty);int i;for (i = 0; i < numClients; i++){// Start 'this' program but spawn a named pipe client.plist[i] = Process.Start(currentProcessName, "spawnclient");}while (i > 0){for (int j = 0; j < numClients; j++){if (plist[j] != null){if (plist[j]!.HasExited){Console.WriteLine($"Client process[{plist[j]?.Id}] has exited.");plist[j] = null;i--; // decrement the process watch count}else{Thread.Sleep(250);}}}}Console.WriteLine("\nClient processes finished, exiting.");}
}// Defines the data protocol for reading and writing strings on our stream.
public class StreamString
{private Stream ioStream;private UnicodeEncoding streamEncoding;public StreamString(Stream ioStream){this.ioStream = ioStream;streamEncoding = new UnicodeEncoding();}public string ReadString(){int len;len = ioStream.ReadByte() * 256;len += ioStream.ReadByte();var inBuffer = new byte[len];ioStream.Read(inBuffer, 0, len);return streamEncoding.GetString(inBuffer);}public int WriteString(string outString){byte[] outBuffer = streamEncoding.GetBytes(outString);int len = outBuffer.Length;if (len > UInt16.MaxValue){len = (int)UInt16.MaxValue;}ioStream.WriteByte((byte)(len / 256));ioStream.WriteByte((byte)(len & 255));ioStream.Write(outBuffer, 0, len);ioStream.Flush();return outBuffer.Length + 2;}
}
2.3 可靠编程
因为此示例中的客户端进程和服务器进程可以在同一台计算机上运行,所以提供给 NamedPipeClientStream 对象的服务器名称为 "."
。 如果客户端进程和服务器进程在不同的计算机上运行,"."
会被替换为运行服务器进程的计算机的网络名称。
相关文章:
【微软技术栈】C#.NET 中的管道操作
C#.NET 管道为进程间通信提供了平台。 管道分为两种类型: 匿名管道。 匿名管道在本地计算机上提供进程间通信。 与命名管道相比,虽然匿名管道需要的开销更少,但提供的服务有限。 匿名管道是单向的,不能通过网络使用。 仅支持一个服…...
Python学习笔记--进程
进程 Python 中的多线程其实并不是真正的多线程,如果想要充分地使用多核 CPU 的资源,在 Python 中大部分情况需要使用多进程。 Python 提供了非常好用的多进程包 multiprocessing,只需要定义一个函数,Python 会完成其他所有事情。 借助这个包,可以轻松完成从单进程到并…...

比亚迪刀片电池与特斯拉4680电池比较
1 电池材料 比亚迪刀片电池采用的磷酸铁锂LFP(LiFePO4),特斯拉的4680电池采用的三元锂。 磷酸铁锂:循环寿命长,安全性能好,价格低廉,但是能量密度低,导电性能差,低温表现…...
在写windows C++代码的时候,从代码安全角度考虑,我们应该注意什么?
在写windows C代码的时候,从代码安全角度考虑,我们应该注意什么?分别是:输入验证、内存管理、错误处理、并发和线程安全、使用安全的API、避免使用不安全的函数、最小权限原则。 一、输入验证 1. 用户输入验证 #include <io…...

【草料】uni-app ts vue 小程序 如何如何通过草料生成对应的模块化二维码
一、查看uni-app项目 1、找到路径 可以看到项目从 src-race-pages-group 这个使我们目标的查询页面 下面我们将这个路径copy到草料内 2、找到进入页面入参 一般我们都会选择 onload() 函数下的入参 这里我们参数的是 id 二、草料 建议看完这里的教程文档 十分清晰!…...
CMS与FullGC
JVM中的CMS(Concurrent Mark Sweep)GC和Full GC(Full Garbage Collection)是两种不同的垃圾回收算法。 CMS GC:CMS GC是一种并发的垃圾回收算法,它在运行期间与应用程序线程并发工作,尽可能减少…...

一款.NET开源的小巧、智能、免费的Windows内存清理工具 - WinMemoryCleaner
前言 我们在使用Windows系统的时候经常会遇到一些程序不会释放已分配的内存,从而导致电脑变得缓慢。今天给大家推荐一款.NET开源的小巧、智能、免费的Windows内存清理工具:WinMemoryCleaner。 使用Windows内存清理工具来优化内存,这样不必浪…...

iptables详解:链、表、表链关系、规则的基本使用
目录 防火墙基本概念 什么是防火墙? Netfilter与iptables的关系 链的概念 表的概念 表链关系 规则的概念 查询规则 添加规则 删除iptables中的记录 修改规则 更详细的命令(5链4表) 防火墙基本概念 什么是防火墙? 在…...
安全管理中心(设备和技术注解)
网络安全等级保护相关标准参考《GB/T 22239-2019 网络安全等级保护基本要求》和《GB/T 28448-2019 网络安全等级保护测评要求》 密码应用安全性相关标准参考《GB/T 39786-2021 信息系统密码应用基本要求》和《GM/T 0115-2021 信息系统密码应用测评要求》 1系统管理 1.1对系统管…...

Failed to execute org.scala-tools:maven-scala-plugin:2.15.2解决
原因也不是很清楚,查看一个博主文章(net.alchim31.maven:scala-maven-plugin:maven依赖无法下载或无法编译)得到的解决方案: 在idea的terminal执行以下语句即可实现maven对scala代码的编译: mvn clean scala:compile compile pac…...
C#中委托和事件的使用总结
委托(delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。事件是一种特殊的多播委托,仅可以从声明事件的类或结构中对其进行调用。类或对象可以通过事件向其他类或对象通知发生的…...

基于STM32的外部中断(EXTI)在嵌入式系统中的应用
外部中断(External Interrupt,EXTI)是STM32嵌入式系统中常见且重要的功能之一。它允许外部事件(例如按键按下、传感器触发等)通过适当的引脚触发中断,从而应用于各种嵌入式系统中。在STM32微控制器中&#…...

【心得】PHP的文件上传个人笔记
目录 1 php的文件上传绕过 黑名单绕过 2 php文件上传的00截断 3 iconv字符转换异常后造成了字符截断 4 文件后缀是白名单的时候的绕过 web服务器的解析漏洞绕过 5.高级文件上传绕过 1 .htaccess nginx.htaccess 2 服务端内容检测 3 配合伪协议来绕过 4.配合日志包含绕…...

深度学习之基于Pytorch和OCR的识别文本检测系统
欢迎大家点赞、收藏、关注、评论啦 ,由于篇幅有限,只展示了部分核心代码。 文章目录 一项目简介深度学习与OCRPyTorch在OCR中的应用文本检测系统的关键组成部分1. 图像预处理2. 深度学习模型3. 文本检测算法4. 后处理 二、功能三、系统四. 总结 一项目简…...

三十一、W5100S/W5500+RP2040树莓派Pico<TCP_Server多路socket>
文章目录 1 前言2 简介2. 1 使用多路socket的优点2.2 多路socket数据交互原理2.3 多路socket应用场景 3 WIZnet以太网芯片4 多路socket设置示例概述以及使用4.1 流程图4.2 准备工作核心4.3 连接方式4.4 主要代码概述4.5 结果演示 5 注意事项6 相关链接 1 前言 W5100S/W5500是一…...

带你精通chrony服务器
华子目录 为什么会出现Chrony?Linux的两个时钟NTP介绍Chrony介绍安装与配置安装Chrony配置文件分析实验1实验2chronyc命令查看时间服务器chronyc sources输出分析其他命令 常见时区 为什么会出现Chrony? 由于IT系统中,准确的计时非常重要&am…...

vs2017 编译Qt 5.11.2 源码
SDK 10.0.22000.194 有 2种编译方式 ,第二种 看下面 方式一: 1、问题描述: 使用VS编译程序时,运行库选择多线程(/MT),表示采用多线程静态release的方式进行编译。 但是,发现编译是不能通过的…...

【SpringBoot3+Vue3】四【实战篇】-前端(vue基础)
目录 一、项目前置知识 二、使用vscode创建 三、vue介绍 四、局部使用vue 1、快速入门 1.1 需求 1.2 准备工作 1.3 操作 1.3.1 创建html 1.3.2 创建初始html代码 1.3.3 参照官网import vue 1.3.4 创建vue应用实例 1.3.5 准备div 1.3.6 准备用户数据 1.3.7 通过…...

element ui修改select选择框背景色和边框色
一、修改选择框的背景色和边框色 style部分 .custom-select /deep/ .el-input__inner {color: #fff!important;border: 1px solid #326AFF;background: #04308D !important; } html部分 <el-select class"custom-select" v-model"dhvalue" placeholde…...
软件测试人员提问常用的ChatGPT通用提示词模板
如何设计有效的软件测试用例? 如何运用自动化测试工具进行软件测试? 如何进行软件的功能测试、性能测试和安全测试? 如何评估软件测试的质量和覆盖范围? 软件测试有哪些常见的缺陷和错误,如何识别和解决࿱…...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明
LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造,完美适配AGV和无人叉车。同时,集成以太网与语音合成技术,为各类高级系统(如MES、调度系统、库位管理、立库等)提供高效便捷的语音交互体验。 L…...

智慧医疗能源事业线深度画像分析(上)
引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...
可靠性+灵活性:电力载波技术在楼宇自控中的核心价值
可靠性灵活性:电力载波技术在楼宇自控中的核心价值 在智能楼宇的自动化控制中,电力载波技术(PLC)凭借其独特的优势,正成为构建高效、稳定、灵活系统的核心解决方案。它利用现有电力线路传输数据,无需额外布…...
生成 Git SSH 证书
🔑 1. 生成 SSH 密钥对 在终端(Windows 使用 Git Bash,Mac/Linux 使用 Terminal)执行命令: ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" 参数说明: -t rsa&#x…...

【2025年】解决Burpsuite抓不到https包的问题
环境:windows11 burpsuite:2025.5 在抓取https网站时,burpsuite抓取不到https数据包,只显示: 解决该问题只需如下三个步骤: 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...

嵌入式学习笔记DAY33(网络编程——TCP)
一、网络架构 C/S (client/server 客户端/服务器):由客户端和服务器端两个部分组成。客户端通常是用户使用的应用程序,负责提供用户界面和交互逻辑 ,接收用户输入,向服务器发送请求,并展示服务…...
深入浅出Diffusion模型:从原理到实践的全方位教程
I. 引言:生成式AI的黎明 – Diffusion模型是什么? 近年来,生成式人工智能(Generative AI)领域取得了爆炸性的进展,模型能够根据简单的文本提示创作出逼真的图像、连贯的文本,乃至更多令人惊叹的…...

在 Visual Studio Code 中使用驭码 CodeRider 提升开发效率:以冒泡排序为例
目录 前言1 插件安装与配置1.1 安装驭码 CodeRider1.2 初始配置建议 2 示例代码:冒泡排序3 驭码 CodeRider 功能详解3.1 功能概览3.2 代码解释功能3.3 自动注释生成3.4 逻辑修改功能3.5 单元测试自动生成3.6 代码优化建议 4 驭码的实际应用建议5 常见问题与解决建议…...

ui框架-文件列表展示
ui框架-文件列表展示 介绍 UI框架的文件列表展示组件,可以展示文件夹,支持列表展示和图标展示模式。组件提供了丰富的功能和可配置选项,适用于文件管理、文件上传等场景。 功能特性 支持列表模式和网格模式的切换展示支持文件和文件夹的层…...

Redis上篇--知识点总结
Redis上篇–解析 本文大部分知识整理自网上,在正文结束后都会附上参考地址。如果想要深入或者详细学习可以通过文末链接跳转学习。 1. 基本介绍 Redis 是一个开源的、高性能的 内存键值数据库,Redis 的键值对中的 key 就是字符串对象,而 val…...