进程间通信之邮件槽

recv:

#include <windows.h>
#include <iostream>
int main()
{
	HANDLE Mailslot;
	char buffer[256];
	DWORD NumberOfBytesRead;
	// 创建邮件槽
	Mailslot = CreateMailslot("\\\\.\\Mailslot\\Myslot", 
		                      0,
		                      MAILSLOT_WAIT_FOREVER, 
		                      NULL);
	if (INVALID_HANDLE_VALUE == Mailslot)
	{
		printf("Failed to create a mailslot %d/n", GetLastError());
		std::cin.get();
		return -1;
	}
	std::cout << "等待接收数据..." << std::endl;

	// 从邮件槽上接收数据
	while (0 != ReadFile(Mailslot, buffer, 256, &NumberOfBytesRead, NULL))
	{
		buffer[NumberOfBytesRead] = '\0';
		std::cout << "接收的数据大小为:" << NumberOfBytesRead << std::endl;
		std::cout << "接收的数据内容为:" << buffer << std::endl;
	}

	// 关闭邮件槽
	CloseHandle(Mailslot);

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

send:

#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
	HANDLE Mailslot;
	DWORD BytesWritten;
	CHAR ServerName[256] = {"\\\\.\\Mailslot\\Myslot"};

	Mailslot = CreateFile(ServerName, GENERIC_WRITE,
		FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (INVALID_HANDLE_VALUE == Mailslot)
	{
		printf("打开命名邮件槽失败,原因: %d\r\n", GetLastError());
		system("pause");
		return -1;
	}
	if (0 == WriteFile(Mailslot, "This is a test", 14, &BytesWritten, NULL))
	{
		printf("向邮件槽发送数据失败,原因: %d\r\n", GetLastError());
		system("pause");
		return -1;
	}
	printf("Wrote %d bytedsr\r\n", BytesWritten);
	CloseHandle(Mailslot);

	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值