我想在兩個不相關的進程之間使用Posix共享內存。Posix在無關進程之間使用mmap共享mem
在下面的代碼將執行以下操作
0.1)創建的共享存儲器與MAP_SHARED標誌段。第36行
.2)基於命令行arg aiType 1或2 - 將一些數據寫入內存。第51行 - 讀取內存中的數據。第56行
.3)msync將數據刷新到內存中。 60號線
。4)munmap和shm_unlink清理66號線和71
問題:無法讀取由另一個進程共享內存中寫入數據
我想兩次運行下面的代碼第一次運行1 - ./test 1,然後作爲run2 - ./test 2
我期待讀取由run1在run2控制檯中寫入的值,但不會發生。 此外,只要RUN2中被啓動* d的值「RUN1變爲0」 63
線當我查看/ proc/PID /圖
inode的價值是相同的兩個過程 - 3014341
RUN1 7f83592ee000-7f83592ef000 RW-S 00000000 0時11分3014341的/ dev/SHM /測試
RUN2 7f740650d000-7f740650e000 RW-S 00000000 0時11分3014341的/ dev/SHM /測試
請讓我知道我缺少
Code
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <sys/file.h>
6 #include <sys/mman.h>
7 #include <sys/wait.h>
8 #include <errno.h>
9
10 void error_and_die(const char *msg) {
11 perror(msg);
12 exit(EXIT_FAILURE);
13 }
14
15 int main(int argc, char *argv[]) {
16 int rc;
17 int aiType = 0;
18
19 const char *memname = "test1";
20 const size_t region_size = sysconf(_SC_PAGE_SIZE);
21 void *ptr;
22 u_long *d;
23
24 int fd = shm_open(memname, O_CREAT | O_TRUNC | O_RDWR, 0666);
25 if (fd == -1)
26 error_and_die("shm_open");
27
28
29 aiType = atoi(argv[1]);
30
31 rc = ftruncate(fd, region_size);
32 printf("errno : %d \n",errno);
33 if (rc != 0)
34 error_and_die("ftruncate");
35
36 ptr = mmap(NULL, region_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
37 printf("ptr ret by : %p \n",ptr);
38
39 if (ptr == MAP_FAILED) {
40 error_and_die("mmap");
41 close(fd);
42 }
43
46
47 d = (u_long *) ptr;
48
49 if(aiType == 1){
50
51 *d = 0xdeadbeef;
52 printf(" Wrote *d : %x \n",*d);
53
54 } else if (aiType == 2){
55
56 printf(" Read *d : %x \n",*d);
57
58 }
59
60 rc = msync(ptr, region_size, MS_SYNC);
61 getchar();
62
63 printf(" *d : %x is \n",*d);
64
65
66 rc = munmap(ptr, region_size);
67 if (rc != 0)
68 error_and_die("munmap");
69
70
71 rc = shm_unlink(memname);
72 if (rc != 0)
73 error_and_die("shm_unlink");
74
75
76 printf("End getchar() \n");
77 getchar();
78
79
80 return 0;
如果可能的話,請不要將行號包含在源代碼中,這會使得難以獲取代碼並嘗試。 – chill
啊好的,會小心 – newbee8