命名管道简单说明

命名管道简单说明

是从网上各个帖子中学习的代码,因此代码的格式以及内容有粘贴网上其他大神的代码,如有侵权请告知删除

与共享内存作用一样,都是为了多进程对同一块信息进行读写操作

服务端:

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;

int main()
{
	//创建命名管道
	HANDLE hPipe = CreateNamedPipe(L"\\\\.\\Pipe\\test",
		PIPE_ACCESS_DUPLEX, //双向管道
		PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, //消息形式写入|消息形式读出|同步操作在等待的时候挂起线程
		1, //最大客户端数
		0, //输出缓冲区长度,0代表默认
		0, //输入缓冲区长度,0代表默认
		NMPWAIT_WAIT_FOREVER, //一直阻塞
		0);
	if (hPipe == NULL)
	{
		DWORD dWErr = GetLastError();
		cout << "The CreateNamedPipe ErrCode is " << dWErr << endl;
		return -1;
	}
	cout << "Create Pipe Success" << endl;

	//等待客户端连接
	if (ConnectNamedPipe(hPipe, NULL) != NULL)
	{
		cout << "Connect Pipe Success" << endl;

		DWORD    dwWrite;
		char *pStr = "This is Created by me[Server]";
		if (!WriteFile(hPipe, pStr, strlen(pStr), &dwWrite, NULL))
		{
			cout << "Server Write Fail" << endl;
			return -1;
		}
		cout << "Server Write String is: " << pStr << endl;
	}
	else
	{
		DWORD dWErr = GetLastError();
		cout << "The ConnectNamedPipe ErrCode is " << dWErr << endl;
		return -1;
	}

	DisconnectNamedPipe(hPipe);
	CloseHandle(hPipe);
	cout << "Close Pipe Success" << endl;
	system("pause");

}

在这里插入图片描述
客户端:

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <ctime>
#include <conio.h>
using namespace std;
#define BUFSIZE 5


int main()
{
	if (WaitNamedPipe(L"\\\\.\\Pipe\\test", NMPWAIT_WAIT_FOREVER) == FALSE)
	{
		cout << "Connect to Server Pipe Fail" << endl;
		return -1;
	}

	HANDLE hPipe = CreateFile(L"\\\\.\\Pipe\\test", 
		GENERIC_READ | GENERIC_WRITE, //允许进行读访问|允许进行写访问
		0,//表示不共享
		NULL, 
		OPEN_EXISTING, //文件必须存在
		FILE_ATTRIBUTE_NORMAL, //默认属性
		NULL);

	if (hPipe == NULL)
	{
		DWORD dWErr = GetLastError();
		cout << "The CreateFile ErrCode is " << dWErr << endl;
		return -1;
	}


	//获取服务端发送的消息
	DWORD dwRead;
	char Buffer[64] = { 0 };
	string recvData = "";
	while (true)
	{
		if (!ReadFile(hPipe, Buffer, 64, &dwRead, NULL))
		{
			cout << "ReadFile Error" << endl;
			return -1;
		}
		cout << "Receive The Server Data:" << Buffer << endl;

	}

	FlushFileBuffers(hPipe);
	DisconnectNamedPipe(hPipe);
	CloseHandle(hPipe);

	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值