2

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?

tedris
  • 41
  • 3
  • 8
  • See also http://stackoverflow.com/q/2389353. – Kerrek SB Mar 14 '16 at 20:05
  • Probably need to improve your search skills. Many answers within and outside stackoverflow. For example: [Is it possible to use mutex in multiprocessing case on Linux/UNIX ?](http://stackoverflow.com/questions/9389730/is-it-possible-to-use-mutex-in-multiprocessing-case-on-linux-unix) – kaylum Mar 14 '16 at 20:09
  • 1
    @kaylum, because it doesn't really solve OP's problem - the first process needs to create a mutex in the shared memory before the second process reads it, and there is no way to ensure mutex is created. – SergeyA Mar 14 '16 at 20:17
  • @SergeyA Ok, fair enough. I have a different interpretation of the question but you may have a point. – kaylum Mar 14 '16 at 20:19

2 Answers2

1

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.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
1

You can create a shared mutex into an mmapped 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.

Community
  • 1
  • 1