Mmap and structure

Tags: c pointers mmap
By : blid
Source: Stackoverflow.com
Question!

I'm working some code including communication between processes, using semaphores. I made structure like this:

typedef struct container {
    sem_t resource, mutex;
    int counter;
} container;

and use in that way (in main app and the same in subordinate processes)

container *memory;

shm_unlink("MYSHM"); //just in case
fd = shm_open("MYSHM", O_RDWR|O_CREAT|O_EXCL, 0);

if(fd == -1) {
    printf("Error");
    exit(EXIT_FAILURE);
}
memory = mmap(NULL, sizeof(container), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
ftruncate(fd, sizeof(container));

Everything is fine when I use one of the sem_ functions, but when I try to do something like

memory->counter = 5;

It doesn't work. Probably I got something wrong with pointers, but I tried almost everything and nothing seems to work. Maybe there's a better way to share variables, structures etc between processes ? Unfortunately I'm not allowed to use boost or something similiar, the code is for educational purposes and I'm intentend to keep as simple as it's possible.

By : blid


Answers

Why are you calling shm_open at all? A pretty good way to do this is to just call 'open' on some pathname and use that.



This video can help you solving your question :)
By: admin