I would like to do multi-process programming where I need to share data (reader/writer case).
My idea is to use shared memory to track read/write index. And the index indicates the shared file index. For example, if write index = 2, it means writer is writing shared file named "temp_2.data". if read index = 1, it means reader is reading shared file named "temp_1.data".
My problem is:
Do I need the synchronization mechanism when, ex: accessing rptr below? or shm_open itself promises the synchronization? If so, how it makes the synchronization?
The hybrid design of shared memory and shared file makes sense? Or if there is any better way?
Thanks~
#include <unistd.h>
#include <sys/mman.h>
...
#define MAX_LEN 10000
struct region { /* Defines "structure" of shared memory */
int len;
char buf[MAX_LEN];
};
struct region *rptr;
int fd;
/* Create shared memory object and set its size */
fd = shm_open("/myregion", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd == -1)
/* Handle error */;
if (ftruncate(fd, sizeof(struct region)) == -1)
/* Handle error */;
/* Map shared memory object */
rptr = mmap(NULL, sizeof(struct region),
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (rptr == MAP_FAILED)
/* Handle error */;
/* Now we can refer to mapped region using fields of rptr;
for example, rptr->len */
...