I have two processes that have data in shared memory. This data is going to be updated by both of these process. I was looking for some locking mechanism between two processes. With threads it was easy to have a shared mutex lock. In my case, I tried to save the mutex variable in the shared memory, which then will be used by both processes for locking. This didn't work though. How do I share a mutex between two processes. Some say mutexes cannot be shared, use semaphores. Why mutex cannot be shared but semaphores can be?
Asked
Active
Viewed 820 times
1 Answers
3
It is possible, you have to use the flag PTHREAD_PROCESS_SHARED:
pthread_mutexattr_t mattr;
pthread_mutexattr_init(&mattr);
pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
// Init the shared mem barrier
if ( (rv = pthread_mutex_init(&nshared, &mattr)) != 0 ) {
fprintf(stderr, "Failed to initiliaze the shared mutex.\n");
return rv;
}
Where the variable nshared
is mapped in shared memory.
Take a look at this documentation. Also, keep in mind that the default value for the mutex is to not share it among processes.
also, take a look at these posts post1 post2
Bonus code to chek the status of the mutex:
void showPshared(pthread_mutexattr_t *mta) {
int rc;
int pshared;
printf("Check pshared attribute\n");
rc = pthread_mutexattr_getpshared(mta, &pshared);
printf("The pshared attributed is: ");
switch (pshared) {
case PTHREAD_PROCESS_PRIVATE:
printf("PTHREAD_PROCESS_PRIVATE\n");
break;
case PTHREAD_PROCESS_SHARED:
printf("PTHREAD_PROCESS_SHARED\n");
break;
default :
printf("! pshared Error !\n");
exit(1);
}
return;
}
I don't remember were I took this piece of code ... found it! here is the source of hal knowledge.

Community
- 1
- 1

terence hill
- 3,354
- 18
- 31