1. 程式人生 > >Windows or Linux環境下利用“共享記憶體”實現程序間通訊的C/C++程式碼

Windows or Linux環境下利用“共享記憶體”實現程序間通訊的C/C++程式碼

程序A對應的程式:

#include <iostream>
#include <windows.h>
using namespace std;

#define BUF_SIZE 1025
char szName[] = "NameOfMappingObject";    // 共享記憶體的名字

int main()
{
	// 建立共享檔案控制代碼
    HANDLE hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,    // 物理檔案控制代碼
        NULL,                    // 預設安全級別
        PAGE_READWRITE,          // 可讀可寫
        0,                       // 高位檔案大小
        BUF_SIZE,                // 地位檔案大小
        szName                   // 共享記憶體名稱
		);


    char *pBuf = (char *)MapViewOfFile(
		hMapFile,            // 共享記憶體的控制代碼
        FILE_MAP_ALL_ACCESS, // 可讀寫許可
        0,
        0,
        BUF_SIZE
		);


    while(1)
    {
	cout << "input..." << endl;
        char szInfo[BUF_SIZE] = {0};
        gets(szInfo); // 其實gets並不安全
        strncpy(pBuf, szInfo, BUF_SIZE - 1);
		pBuf[BUF_SIZE - 1] = '\0';
    }

	UnmapViewOfFile(pBuf);
    CloseHandle(hMapFile);
	return 0;
}

程序B對應的程式:

#include <iostream>
#include <windows.h>
using namespace std;

#define BUF_SIZE 1025
char szName[] = "NameOfMappingObject";    // 共享記憶體的名字

int main()
{
	// 建立共享檔案控制代碼
    HANDLE hMapFile = OpenFileMapping(
        INVALID_HANDLE_VALUE,    // 物理檔案控制代碼
        NULL,                    // 預設安全級別
        PAGE_READWRITE,          // 可讀可寫
        0,                       // 高位檔案大小
        BUF_SIZE,                // 地位檔案大小
        szName                   // 共享記憶體名稱
		);


    char *pBuf = (char *)MapViewOfFile(
		hMapFile,            // 共享記憶體的控制代碼
        FILE_MAP_ALL_ACCESS, // 可讀寫許可
        0,
        0,
        BUF_SIZE
		);

    while(1)
    {
        cout << "press any button to receive data..." << endl;
        getchar();
		cout << pBuf << endl;
    }

	UnmapViewOfFile(pBuf);
    CloseHandle(hMapFile);
	return 0;
}

結果: