Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do forked child processes use the same semaphore?

Let's say I create a semaphore. If I fork a bunch of child processes, will they all still use that same semaphore?

Also, suppose I create a struct with semaphores inside and forked. Do all the child processes still use that same semaphore? If not, would storing that struct+semaphores in shared memory allow the child processes to use the same semaphores?

I'm really confused about how my forked child processes can use the same semaphores.

like image 341
jmnwong Avatar asked Jul 27 '11 16:07

jmnwong


1 Answers

Let's say I create a semaphore. If I fork a bunch of child processes, will they all still use that same semaphore?

If you are using a SysV IPC semaphore (semctl), then yes. If you are using POSIX semaphores (sem_init), then yes, but only if you pass a true value for the pshared argument on creation and place it in shared memory.

Also, suppose I create a struct with semaphores inside and forked. Do all the child processes still use that same semaphore? If not, would storing that struct+semaphores in shared memory allow the child processes to use the same semaphores?

What do you mean be 'semaphores inside'? References to SysV IPC semaphores will be shared, because the semaphores don't belong to any process. If you're using POSIX semaphores, or constructing something out of pthreads mutexes and condvars, you will need to use shared memory, and the pshared attribute (pthreads has a pshared attribute for condvars and mutexes as well)

Note that anonymous mmaps created with the MAP_SHARED flag count as (anonymous) shared memory for these purposes, so it's not necessary to actually create a named shared memory segment. Ordinary heap memory will not be shared after a fork.

like image 61
bdonlan Avatar answered Sep 30 '22 07:09

bdonlan