Windows 进程间通信 共享内存

向内存中写数据

 1 // SharedMemorySample_write_main.cpp
 2 #include <SDKDDKVer.h>
 3 #include <Windows.h>
 4 #include <stdio.h>
 5 
 6 int main(int argc, char* argv[])
 7 {
 8     int        shmem_size = 16;  // 16byte
 9     HANDLE    shmem = INVALID_HANDLE_VALUE;
10     HANDLE    mutex = INVALID_HANDLE_VALUE;
11 
12     mutex = ::CreateMutex(NULL, FALSE, "mutex_sample_name");
13 
14     shmem = ::CreateFileMapping(
15         INVALID_HANDLE_VALUE,
16         NULL,
17         PAGE_READWRITE,
18         0,
19         shmem_size,
20         "shared_memory_name"
21         );
22 
23     char *buf = (char*)::MapViewOfFile(shmem, FILE_MAP_ALL_ACCESS, 0, 0, shmem_size);
24 
25 
26     for (unsigned int c = 0; c < 60; ++c) {
27         // mutex lock
28         WaitForSingleObject(mutex, INFINITE);
29 
30         // write shared memory
31         memset(buf, c, shmem_size);
32 
33         printf("write shared memory...c=%d\n", c);
34 
35         // mutex unlock
36         ::ReleaseMutex(mutex);
37 
38         ::Sleep(1000);
39     }
40 
41     // release
42     ::UnmapViewOfFile(buf);
43     ::CloseHandle(shmem);
44     ::ReleaseMutex(mutex);
45 
46     return 0;
47 }

 

从内存中读数据

 1 // SharedMemorySample_read_main.cpp
 2 #include <SDKDDKVer.h>
 3 #include <Windows.h>
 4 #include <stdio.h>
 5 
 6 int main(int argc, char* argv[])
 7 {
 8     int        shmem_size = 16;  // 16byte
 9     HANDLE    shmem = INVALID_HANDLE_VALUE;
10     HANDLE    mutex = INVALID_HANDLE_VALUE;
11 
12     mutex = ::CreateMutex(NULL, FALSE, "mutex_sample_name");
13 
14     shmem = ::CreateFileMapping(
15         INVALID_HANDLE_VALUE,
16         NULL,
17         PAGE_READWRITE,
18         0,
19         shmem_size,
20         "shared_memory_name"
21         );
22 
23     char *buf = (char*)::MapViewOfFile(shmem, FILE_MAP_ALL_ACCESS, 0, 0, shmem_size);
24 
25 
26     for (unsigned int c = 0; c < 60; ++c) {
27         // mutex lock
28         WaitForSingleObject(mutex, INFINITE);
29 
30         printf("read shared memory...c=%d\n", buf[0]);
31 
32         // mutex unlock
33         ::ReleaseMutex(mutex);
34 
35         ::Sleep(1000);
36     }
37 
38     // release
39     ::UnmapViewOfFile(buf);
40     ::CloseHandle(shmem);
41     ::ReleaseMutex(mutex);
42 
43     return 0;
44 }

 

posted @ 2019-09-25 11:05  希广闻  阅读(359)  评论(0编辑  收藏  举报