Windows系统IPC进程间共享内存实现

服务端:

#include "windows.h"
#include "stdio.h"

#define SHARE_MEMORY_NAME "share_memory_channel_i"
#define SHARE_MEMORY_MAX_SIZE 3840*2160*4
LPVOID share_memory_p_data = NULL;

int main(int argc, char* argv[])
{
    HANDLE hMap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, SHARE_MEMORY_MAX_SIZE, SHARE_MEMORY_NAME);
    if (hMap == NULL)
    {
        printf("CreateFileMappingA error\n");
        CloseHandle(hMap);
        hMap = NULL;
        return 0;
    }

 
    LPVOID share_memory_p_data = NULL;
    share_memory_p_data = (CHAR*)MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
    if (share_memory_p_data == NULL)
    {
        printf("view map error!");
        return 0;
    }

    int* p = (int *)share_memory_p_data;
    while (1)
    {
        if (!p[0]) {
            int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
            memcpy(share_memory_p_data, a, 40);
        
        }
        Sleep(3000);
    }

    UnmapViewOfFile((LPCVOID)share_memory_p_data);
    share_memory_p_data = NULL;
    CloseHandle(hMap);

    return 0;
}

客户端:

#include "windows.h"
#include "stdio.h"

#define SHARE_MEMORY_NAME "share_memory_channel_i"
#define SHARE_MEMORY_MAX_SIZE 3840*2160*4
LPVOID share_memory_p_data = NULL;


int main(int argc, char* argv[])
{
    HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, SHARE_MEMORY_NAME);
    if (hMap == NULL)
    {
        printf("hMap error\n");
        CloseHandle(hMap);
        hMap = NULL;
        return 0;
    }


    share_memory_p_data = (CHAR*)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    if (share_memory_p_data == NULL)
    {
        printf("view map error!");
        return 0;
    }


    int* p = (int*)share_memory_p_data;
    while (1)
    {
        if (p[0]) {
            for (int i = 0; i < 10;i++) {
            
                printf("%d\n", p[i]);
            }
            
            int a[1] = { 0 };
            memcpy(share_memory_p_data, a, 4);

        }
        Sleep(300);
    }

    UnmapViewOfFile((LPCVOID)share_memory_p_data);
    share_memory_p_data = NULL;
    CloseHandle(hMap);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值