MFC学习 进程间通信

内存共享通信方式

server.cpp

#include <stdio.h>

#include <Windows.h>

int main()

{

    HANDLE hFile;

    hFile = CreateFile("tmpfile", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,

        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);

    if(hFile == INVALID_HANDLE_VALUE)

    {

        printf("create file failed");

        system("pause");

        return 0;

    }

    

    DWORD dwWrite;

    WriteFile(hFile, "test data", strlen("test data") + 1, &dwWrite, NULL);

    

    HANDLE hFileMapping;

    hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, "mytestfilemapping");

    if(hFileMapping == NULL)

    {



        CloseHandle(hFile);

        

        printf("Create file mapping failed!");

        system("pause");

        return 0;

    }

    /* 可以在这里面修改pfile

    char * pFile = (char*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);

    if(pFile == NULL)

    {

        CloseHandle(hFileMapping);

        CloseHandle(hFile);

        printf("map view of file failed!");

        system("pause");

        return 0;

    }

    */

    Sleep(5000);

    CloseHandle(hFile);

    CloseHandle(hFileMapping);

    

    system("pause");

    return 0;

}

client.cpp

#include <stdio.h>

#include <Windows.h>

int main()

{

    HANDLE hFile;

    hFile = CreateFile("tmpfile", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,

        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);

    if(hFile == INVALID_HANDLE_VALUE)

    {

        printf("create file failed");

        system("pause");

        return 0;

    }

    

    DWORD dwWrite;

    WriteFile(hFile, "test data", strlen("test data") + 1, &dwWrite, NULL);

    

    HANDLE hFileMapping;

    hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, "mytestfilemapping");

    if(hFileMapping == NULL)

    {



        CloseHandle(hFile);

        

        printf("Create file mapping failed!");

        system("pause");

        return 0;

    }

    /* 可以在这里面修改pfile

    char * pFile = (char*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);

    if(pFile == NULL)

    {

        CloseHandle(hFileMapping);

        CloseHandle(hFile);

        printf("map view of file failed!");

        system("pause");

        return 0;

    }

    */

    Sleep(5000);

    CloseHandle(hFile);

    CloseHandle(hFileMapping);

    

    system("pause");

    return 0;

}

例子包括剪切板,  匿名管道(父子进程通信), 命名管道, 油槽(单向, 但可以一边同时建立服务与客户端),  内存共享

源码下载

你可能感兴趣的:(mfc)