C 使用共享記憶體實現程序間通訊

2021-06-14 02:15:50 字數 2910 閱讀 2398

server完整原始碼:

#pragma region includes

#include #include #pragma endregion

#define map_prefix l"local\\"

#define map_name l"samplemap"

#define full_map_name map_prefix map_name

#define map_size 65536

// file offset where the view is to begin.

#define view_offset 0

#define view_size 1024

// must be less than the view size (view_size).

#define message l"message from the first process."

int wmain(int argc, wchar_t* argv)

// process.

pview = mapviewoffile(

hmapfile, // handle of the map object

file_map_all_access, // read and write access

0, // high-order dword of the file offset

view_offset, // low-order dword of the file offset

view_size // the number of bytes to map to view

);if (pview == null)

// prepare a message to be written to the view.

pwstr pszmessage = message;

dword cbmessage = (wcslen(pszmessage) + 1) * sizeof(*pszmessage);

// write the message to the view.

memcpy_s(pview, view_size, pszmessage, cbmessage);

wprintf(l"this message is written to the view:\n\"%s\"\n",

pszmessage);

// wait to clean up resources and stop the process.

wprintf(l"press enter to clean up resources and quit");

getchar();

cleanup:

if (hmapfile)

closehandle(hmapfile);

hmapfile = null;

}return 0;

}

client完整原始碼

#pragma region includes

#include #include #pragma endregion

#define map_prefix l"local\\"

#define map_name l"samplemap"

#define full_map_name map_prefix map_name

// file offset where the view is to begin.

#define view_offset 0

#define view_size 1024

int wmain(int argc, wchar_t* argv)

// process.

pview = mapviewoffile(

hmapfile, // handle of the map object

file_map_read, // read access

0, // high-order dword of the file offset

view_offset, // low-order dword of the file offset

view_size // the number of bytes to map to view

);if (pview == null)

// read and display the content in view.

// wait to clean up resources and stop the process.

wprintf(l"press enter to clean up resources and quit");

getchar();

cleanup:

if (hmapfile)

closehandle(hmapfile);

hmapfile = null;

}return 0;

}

執行效果:

共享記憶體實現程序間通訊

1 物理檔案控制代碼 任何可以獲得的物理檔案控制代碼,如果你需要建立乙個物理檔案無關的記憶體對映也無妨,將它設定成為 0xffffffff invalid handle value 就可以了.如果需要和物理檔案關聯,要確保你的物理檔案建立的時候的訪問模式和 保護設定 匹配,比如 物理檔案唯讀,記憶體...

程序間通訊 共享記憶體

下面是自己寫的乙個簡單的共享記憶體的程序間通訊的例子。共享記憶體是用於程序間大量資料共享的一種方法。include include include include include include int main if buf1 shmat shmid,0,0 void 1 strcpy buf1,...

程序間通訊 共享記憶體

共享記憶體是被多個程序共享的一部分物理記憶體。共享記憶體是程序間共享資料的一種最快的方式,乙個程序向共享記憶體區域寫入資料,共享這個記憶體區域的所有程序就可以立刻看到其中的內容。共享記憶體實現分兩個步驟 建立共享記憶體,使用shmget函式 對映共享記憶體,使用shmat函式 共享記憶體是一種最為高...