进程间通信之命名管道

server:

#include <stdio.h>
#include <conio.h>  
#include <tchar.h>
#include <Windows.h>
#include <process.h>
#include <stdlib.h>
#include <iostream>
const char *pStrPipeNameGet = "\\\\.\\pipe\\recv_data_pipe";// 注意命名管道的规则:\\servername\pipe\pipename,如果是本地管道则servername可以使用点“.”
HANDLE hSemaphore;

void RecvDataThread(PVOID p) 
{
	printf("管道服务器已经启动,等待连接...\n");

	// 创建一个命名管道
	HANDLE hPipe = CreateNamedPipe(pStrPipeNameGet, // 管道的名称
		                           PIPE_ACCESS_DUPLEX,// 管道的打开模式
		                           PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,// 管道的使用模式
		                           PIPE_UNLIMITED_INSTANCES, // 管道可以接收的最大客户量
		                           0, // 输出缓冲区长度;零表示用默认设置
		                           0, // 输入缓冲区长度;零表示用默认设置
		                           NMPWAIT_WAIT_FOREVER, // 管道的默认等待超时
		                          NULL);// 安全属性结构
	
	const int BUFFER_MAX_LEN = 1024;
	DWORD dwRecvDataLen;
	char buf[BUFFER_MAX_LEN];
	// 等待客户端管道的连接
	if (ConnectNamedPipe(hPipe, NULL) != NULL)  
	{
		printf("连接成功,开始接收数据\n");
		while (true)
		{
			// 接收客户端发送的数据  
			if (!ReadFile(hPipe, buf, BUFFER_MAX_LEN, &dwRecvDataLen, NULL))
				break;
			printf("接收到来自客户端的数据长度为%d字节\n", dwRecvDataLen);
			printf("具体数据内容如下:");
			std::cout << buf << std::endl;
		}
	}
	else
	{
		printf("连接失败\n");
	}

	// 断开所有与命名管道上的连接
	DisconnectNamedPipe(hPipe);

	// 关闭命名管道
	CloseHandle(hPipe);

	ReleaseSemaphore(hSemaphore, 1, NULL);
}

int _tmain(int argc, _TCHAR* argv[])
{
	hSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("my_semaphore"));
	_beginthread(RecvDataThread, NULL, NULL);
	WaitForSingleObject(hSemaphore, INFINITE);

	std::cout << "按任意键退出." << std::endl;
	std::cin.get();
	return 0;
}



client:

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <conio.h>  
#include <iostream>
const char *pStrPipeName = "\\\\.\\pipe\\recv_data_pipe";
const int BUFFER_MAX_LEN = 1024;
char buf[BUFFER_MAX_LEN];

int _tmain(int argc, _TCHAR* argv[])
{
	printf("等待管道服务器......\r\n");
	if (!WaitNamedPipe(pStrPipeName, 100000))
	{
		printf("连接管道服务器失败.\r\n");
		std::cin.get();
		return 0;
	}
	HANDLE hPipe = CreateFile(pStrPipeName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	while (true)
	{
		printf("请输入要向服务端发送的数据,回车键结束,最大1024个字节\r\n");
		DWORD dwLen = 0;
		int bufSize;
		std::cin >> buf;
		bufSize = strlen(buf)+1;
		buf[bufSize] = '\0';
		//向服务端发送数据  
		if (WriteFile(hPipe, buf, bufSize, &dwLen, NULL)) {
			printf("数据写入完毕共%d字节\r\n", dwLen);
		}
		else
		{
			printf("数据写入失败\n");
		}
		if (strcmp(buf, "exit") == 0)
			break;
	}
	CloseHandle(hPipe);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值