fork

Semaphores + Fork + Linux in C++

roland's picture

So, I waisted over a week trying to figure out shared memory semaphores in linux.

The only way semaphores are shared in memory is by giving them names and then doing a sem_open to open the memory address. Then you use sem_init to initialize.

There's another way of working the shared memory; that is using mmap.

The way mmap works is:

int file_descriptor = open( ... );
write(filename, sem_t something, 1); /// This is a bit weird. You write binary data to a file
unlink(filename);

then mmap(.... pass fd=file_descriptor... )

This will make sem_t available to all processes that have been forked.

Now, I didn't try it with mmap this particular example, but i have made a linked list with mmap.

It seems I finally understood how mmap works. Basically, you can write a size of N of something (Node *) in memory. Then you can iterate through each object and place pointers accordingly.

Syndicate content