Reputation: 41
I have two processes that will be running, one that will be reading from shared memory (mmap) and one that will be writing to that shared memory (mmap). These processes are started separately in two different terminals, but they need to be synchronized so that while one process is writing, it writes the full amount before the other process reads from the memory. All of the posts I have seen relating to shared memory mutex locks have been spawning threads/processes from a single main program. Is there any way to create a shared mutex lock that can be used by two separate programs?
Upvotes: 2
Views: 10629
Reputation: 133859
You can create a shared mutex into an mmap
ped file. If you're using Linux and have a sufficiently new kernel, you can even create an unlinked temp file, mmap
it; initialize the mutex and only then link it to the final location. Or you can use file locking to deny access to it until the initialization has been completed.
The semaphore example from pthread_mutexattr_init
POSIX manuals at linux.die.net did work on my Linux 4.2.0-27 Ubuntu.
Upvotes: 1
Reputation: 62553
Sorry, but you are out of luck. Pthreads library does not have a concept of 'named' mutex, so two independent processes can't reliably share one.
Yes, you can create a mutex in shared memory and than use this mutex from the other process, but there is no way you can ensure the mutex is fully initialized by the first process when you are checking it in the second. For trully independent programms I strongly recommend using semaphores.
Upvotes: 1