邮槽-进程间通信
邮槽通信(MailSlot)
邮槽,又称邮件槽,是Windows上一种进程间的通信,是单向的,客户端发送,服务端接收.client.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#define MAILSLOT "\\\\.\\mailslot\\hello" //邮槽使用格式 \\.\\邮槽名称
int main(int argc, char *argv[])
{
HANDLE hd = CreateFileA(MAILSLOT, GENERIC_WRITE, \
FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hd == INVALID_HANDLE_VALUE)
{
printf("无法打开文件!\n");
}
while (1)
{
printf("请输入消息:");
char str[64] = { 0 };
scanf("%s", str);
DWORD writeCount = 0;
WriteFile(hd, str, 64, &writeCount, NULL);
}
CloseHandle(hd);
system("pause");
return 0;
}
server.c
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#define MAILSLOT "\\\\.\\mailslot\\hello" //邮槽使用格式 \\.\\邮槽名称
int main(int argc, char *argv[])
{
HANDLE hd = CreateMailslotA(MAILSLOT, 0, MAILSLOT_WAIT_FOREVER, NULL);
if (hd == NULL)
{
printf("创建邮槽失败!\n");
return 0;
}
while (1)
{
DWORD nextSize = 0;
DWORD msgCount = 0;
DWORD readCount = 0;
if (GetMailslotInfo(hd, NULL, &nextSize, &msgCount, NULL))
{
for (int i = 0; i < msgCount; i++)
{
void * str = malloc(nextSize + 1);
ReadFile(hd, str, nextSize, &readCount, NULL);
printf("%s \n",str);
}
}
}
CloseHandle(hd);
system("pause");
return 0;
}
秋风
2016-07-19