您的位置:首页 > 编程语言 > C语言/C++

win平台C语言油槽通信

2016-06-22 01:14 302 查看
进程通信、共享内存

    进程与进程之间是不能互相读写内存的,所以需要用到进程通信。
    在这种情况下就需要油槽通信,也可以用mutex。

服务端:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

#define MAILSLOT "\\\\.\\mailslot\\eli"

int main()
{
//名称 数量 等待时间 安全属性
//CreateMailslot(MAILSLOT, 0, MAILSLOT_WAIT_FOREVER,NULL)
HANDLE hmailslot = CreateMailslotA(MAILSLOT, 0, MAILSLOT_WAIT_FOREVER,NULL);

if(hmailslot == NULL)
{
printf("创建失败");
return -1;
}

while(1)
{
system("pause");
DWORD dxNextsize = 0; //标识下一个
DWORD dxmsgcount = 0; //消息数量
DWORD readcount = 0; //读取的数量

//文件名 NULL 标记下一个字符串长度 消息条数 NULL
if (GetMailslotInfo(hmailslot, NULL, &dxNextsize, &dxmsgcount, NULL))
{
int i = 0;
for(; i< dxmsgcount; i++)
{
// LPBYTE unsigned char *
LPBYTE lpbuf = malloc(dxNextsize + 1);
//首地址 大小 读的个数
ReadFile(hmailslot, lpbuf, dxNextsize, &readcount, NULL);

printf("%s\n", lpbuf);
}
}
else
{
printf("获取失败!\n");
}
}

}
客户端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

#define MAILSLOT "\\\\.\\mailslot\\eli"

void main()
{

//CreateFileA
//名称 写入 共享读 null 打开已经存在
HANDLE hmailslot = CreateFileA(MAILSLOT, \
GENERIC_WRITE, FILE_SHARE_READ, NULL,OPEN_EXISTING, 0, NULL);

if (hmailslot == INVALID_HANDLE_VALUE)
{
printf("打开失败\n");
}

char str[10] = {0};

while(1)
{
scanf("%s", str);
LPBYTE lpmsg = (LPBYTE)str;

int wok = 0;
//句柄 写入的内存首地址 长度 写入成功长度
WriteFile(hmailslot, lpmsg, 10, &wok, NULL);

}
CloseHandle(hmailslot);

system("pause");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息