windows使用管道简单示例

7 篇文章 0 订阅

环境: windows10 + vs2015


参考:
https://zhuanlan.zhihu.com/p/386564892


下面是命名管道的服务器以及客户端代码:

服务端

#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
	const char *pStrPipeName = "\\\\.\\pipe\\MyNamePipe";

	// 创建管道
	HANDLE hPipe = CreateNamedPipe(pStrPipeName, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, NMPWAIT_WAIT_FOREVER, 0);
	if (hPipe != INVALID_HANDLE_VALUE) {
		printf("Successfully created pipe!\n");
		printf("Waiting for client to connect...\n");
	}

	// 等待客户端连接
	if (ConnectNamedPipe(hPipe, NULL) != NULL) {
		printf("The connection is successful!\n");
		printf("Start to receive data:\n");

		CHAR Buffer[1024] = { 0 };
		DWORD dwNumberOfBytesRead = 0;

		// 接收客户端发送的数据
		ReadFile(hPipe, Buffer, sizeof(Buffer), &dwNumberOfBytesRead, NULL);
		printf("data len: %d\n", dwNumberOfBytesRead);
		printf("content:%s\n", Buffer);

		// 确认已收到数据
		printf("Send a received flag to the client!\n");
		strcpy_s(Buffer, "done");
		WriteFile(hPipe, Buffer, strlen(Buffer) + 1, &dwNumberOfBytesRead, NULL);
	}

	// 断开连接并关闭管道
	DisconnectNamedPipe(hPipe);
	CloseHandle(hPipe);

	cin.get();
	return 0;
}

客户端

#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
	const char *pStrPipeName = "\\\\.\\pipe\\MyNamePipe";

	printf("Connecting to pipe...\n");
	if (WaitNamedPipe(pStrPipeName, NMPWAIT_WAIT_FOREVER) == FALSE) {
		printf("Failed to connect to pipe!\n");
		return 0;
	}

	printf("Open pipe!\n");
	HANDLE hPipe = CreateFile(pStrPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	printf("Send data to the server!\n");

	CHAR Buffer[1024] = { 0 };
	DWORD dwNumberOfBytesWritten = 0;

	// 向服务端发送数据
	sprintf_s(Buffer, "Process %d said: %s", GetCurrentProcessId(), "Hello World!");
	WriteFile(hPipe, Buffer, strlen(Buffer) + 1, &dwNumberOfBytesWritten, NULL);
	printf("Send data len :%d \n", dwNumberOfBytesWritten);

	// 接收服务端发回的数据
	ReadFile(hPipe, Buffer, sizeof(Buffer), &dwNumberOfBytesWritten, NULL);
	printf("Reply data len: %d\n", dwNumberOfBytesWritten);
	printf("content:%s\n", Buffer);

	CloseHandle(hPipe);

	cin.get();
	return 0;
}

说明: 先启动服务端,再启动客户端.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个简单的 Python 程序示例,用于在 Windows使用命名管道进行数据双向通信: ``` import os, msvcrt # 创建命名管道 pipe_name = "\\\\.\\pipe\\mypipe" os.mkfifo(pipe_name) # 父进程写入数据 with open(pipe_name, "w") as pipe: pipe.write("Hello, World!") # 子进程读取数据 with open(pipe_name, "r") as pipe: data = pipe.read() print(data) # 删除命名管道 os.remove(pipe_name) ``` 这段程序中,我们首先使用 os.mkfifo() 函数创建了一个名为 "mypipe" 的命名管道。之后,在父进程中使用 open() 函数打开管道进行写入操作,在子进程中使用 open() 函数打开管道进行读取操作。最后,使用 os.remove() 函数删除了命名管道。 注意: 由于 Windows 中命名管道的实现有所不同,所以在 Windows使用命名管道时需要使用 "\\\\.\\pipe\\" 前缀来指定管道的路径。 ### 回答2: 在Windows上,Python可以使用命名管道实现数据的双向通信。下面是一个使用Python建立命名管道进行双向通信的示例。 首先,我们需要导入所需的模块: ```python import os import win32pipe import win32file import win32event import pywintypes import threading ``` 然后,定义一个用于读取客户端发送数据的函数: ```python def read_from_pipe(pipe): while True: try: data = win32file.ReadFile(pipe, 4096) print("收到客户端发送的数据:", data[1].decode()) except pywintypes.error as e: if e.winerror == 232: # PIPE_BROKEN print("管道已关闭") break ``` 接下来,定义一个用于向客户端发送数据的函数: ```python def write_to_pipe(pipe): while True: try: message = input("请输入要发送给客户端的数据:") win32file.WriteFile(pipe, message.encode()) except pywintypes.error as e: if e.winerror == 232: # PIPE_BROKEN print("管道已关闭") break ``` 然后,在主函数中创建命名管道、启动读取和写入管道的线程: ```python def main(): pipe_name = r'\\.\pipe\my_pipe' pipe = win32pipe.CreateNamedPipe( pipe_name, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT, 1, # maximum number of instances 4096, # output buffer size 4096, # input buffer size 0, # default time out None # default security attributes ) win32pipe.ConnectNamedPipe(pipe, None) read_thread = threading.Thread(target=read_from_pipe, args=(pipe,)) write_thread = threading.Thread(target=write_to_pipe, args=(pipe,)) read_thread.start() write_thread.start() read_thread.join() write_thread.join() win32pipe.DisconnectNamedPipe(pipe) win32pipe.CloseHandle(pipe) if __name__ == "__main__": main() ``` 现在,我们可以运行该脚本,在终端上输入要发送给客户端的数据,然后在另一个终端上查看收到的数据。 请注意,在此示例中,管道的名称是“\\.\pipe\my_pipe”,可以根据需要修改。此外,由于管道是阻塞方式的,所以在读取和写入管道时,程序会一直等待,直到有数据到达或发送成功。 希望这个示例可以帮助你理解如何使用Python在Windows上进行命名管道的双向通信。 ### 回答3: Python在Windows系统中可以使用命名管道(Named Pipe)来实现双向数据通信。命名管道是一种特殊类型的文件,用于进程间或机器间通信。 下面是一个Python在Windows系统中使用命名管道实现双向数据通信的示例: 1. 创建命名管道: ``` import win32pipe import win32file pipe_name = r'\\.\pipe\my_pipe' pipe = win32pipe.CreateNamedPipe(pipe_name, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, win32pipe.PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, None) ``` 2. 连接命名管道: ``` win32pipe.ConnectNamedPipe(pipe, None) ``` 3. 从命名管道中读取数据: ``` data = win32file.ReadFile(pipe, 65536, None) ``` 4. 向命名管道中写入数据: ``` data_to_send = b'Message to send' win32file.WriteFile(pipe, data_to_send) ``` 5. 关闭命名管道: ``` win32file.CloseHandle(pipe) ``` 上述代码中,通过`CreateNamedPipe`函数创建了一个命名管道使用`ConnectNamedPipe`函数连接管道。然后,可以使用`ReadFile`函数从管道中读取数据,使用`WriteFile`函数向管道中写入数据。最后,使用`CloseHandle`函数关闭管道。 需要注意的是,以上示例只是一个简单示例,实际使用时可能需要考虑处理异常、多线程等情况。 希望以上内容对您有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值