进程间通讯 —— 共享内存

通过内存共享的方式来进行进程之间的通讯,可以通过发送端进程在接收端进程中开辟一段内存空间,然后往该内存空间内写入数据,并通知接收端读取数据来达到。

 

实现代码片段

 

发送端:

 

BOOL SendProcessMessage()
{
    HWND hWnd;

    hWnd = FindWindow(NULL, "Recv");  // 查找接收端窗口

    if (!hWnd)
    {
        MessageBox(g_hWnd, "找不到通信进程", "error", MB_OK | MB_ICONERROR);
        return FALSE;
    }

    DWORD dwProcessId;
    GetWindowThreadProcessId(hWnd, &dwProcessId);  // 获取句柄窗口所在进程ID
    
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);  // 获取进程句柄

    if (!hProcess)
    {
        MessageBox(g_hWnd, "打开进程失败", "error", MB_OK | MB_ICONERROR);
        return FALSE;
    }

    LPVOID lpAddress = VirtualAllocEx(hProcess, NULL, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);  // 在目标进程中申请一段内存空间

    if (!lpAddress)
    {
        MessageBox(g_hWnd, "在进程中分配内存失败", "error", MB_OK | MB_ICONERROR);
        return FALSE;
    }

    char buf[] = "hello world!";

    if (!WriteProcessMemory(hProcess, lpAddress, buf, sizeof(buf), NULL))  // 在内存空间中写入内容
    {
        MessageBox(g_hWnd, "在进程分配内存中写入数据失败", "error", MB_OK | MB_ICONERROR);
        return FALSE;
    }

    SendMessage(hWnd, WM_READMEMORY, NULL, (LPARAM)lpAddress);  // 向目标窗口发送消息

    Sleep(100);  // 放弃CPU执行时间片给其它进程

    VirtualFreeEx(hProcess, lpAddress, 0, MEM_RELEASE);  // 释放内存

    return TRUE;
}

 

接收端:

case WM_READMEMORY:

    char buf[1024];

    ReadProcessMemory(GetCurrentProcess(),  (LPVOID)lParam,  buf,  sizeof(buf),  NULL);  // 在内存中读取数据

    MessageBox(g_hWnd, buf, "", MB_OK);

    break;

 

 

posted @ 2012-08-27 23:19  kaixiang54  阅读(271)  评论(0编辑  收藏  举报