I want to use Posix shared memory between two unrelated processes.
The below code does the following
.1) Created a shared memory segment with MAP_SHARED flag. Line 36
.2) based on command line arg aiType 1 or 2 - write some data into memory . Line 51 - read the data in memory . Line 56
.3) msync to flush data into memory . Line 60
.4) munmap and shm_unlink to clean up Line 66 and 71
The issue : Not able to read data written by another process in Shared Memory
I want to run the below code twice first run1 - ./test 1 and then as run2 - ./test 2
I was expecting to read value written by run1 in run2 console BUT THAT DOES NOT HAPPEN. Also, as soon as run2 is started the value of *d in "run1 becomes 0" Line 63
When i look at /proc/pid/maps
The Inode value is same for both the processes - 3014341
run1 7f83592ee000-7f83592ef000 rw-s 00000000 00:11 3014341 /dev/shm/test
run2 7f740650d000-7f740650e000 rw-s 00000000 00:11 3014341 /dev/shm/test
Please let me know what i am missing
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;
Do not shm_unlink
the shared memory object, you're deleting it and each run starts with a fresh one.
PS. And also do not truncate it via the O_TRUNC
in the shm_open
.