I am trying to understand how inter-process communication works with pthread_mutex I've read a bunch of info on the topic but I still cannot wrap my head around it.
I understand that there seems to be an easier way using semaphores but I am not trying to use that but to learn how mmap and inter-process communication works in C.
Let's say I have the following code in "Process 1"
...
if (!initialized) {
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
pthread_mutex_init(&mtx->mtx, &attr);
// save to shared memory
} else {
// get the mutex from shared memory
}
...
Then I start the a copy of the same process and want to check if the mutex is already initialized and in shared memory. How to:
- Initialize the mutex only in the first process and not try to initialize it in the next ones
- Allocate the memory with mmap.