Hypothetically I have created several applications on Mac OS X which use one shared resource or service. In my applications I want to check if the service or resource is created already in the same way as named mutex being used on Windows in order not to create it everywhere. What's the best way to do it in Cocoa?
-
@MattBall - not really a duplicate of that question I think as here the OP has "several" applications, not multiple instances of the same app. However the suggestions in that question (but not answered there) might be applicable here... – CRD Apr 09 '13 at 04:56
2 Answers
If all you wish to do is control access to a shared resource a common Unix/OS X may is to create & lock a file - the file can be zero bytes long.
The system-level way of doing this is to use flock
(manual pages section 2), the C-level way is to use the stdio flockfile
(manual pages section 3), I think all the framework-level ways have been deprecated but I might be wrong (Apple appears to be in the process of changing how filesystem operations are supported but has deprecated some before supplying replacements).
Note: file locking is not the same as Finder-level locking - the former gives you a mutex, the latter is to do with preventing modification.

- 52,522
- 5
- 70
- 86
-
After some test, it seems flockfile is most used for multiple threads in one process because it's only locked for file descriptor, not file itself. In my case, flock will do the work. Thank you! – ken Apr 23 '13 at 16:27
-
@ken - The lock is done on an open file *via* the file descriptor, but is a lock on the file itself. You cannot lock a file you don't have open and closing a locked file will release the lock. So a distinct process will see the lock but the lock is also tied to a process, when that process goes so does the lock. – CRD Apr 23 '13 at 20:38
The most direct analog for a named mutex is a POSIX semaphore. Start with the man page for sem_open().

- 88,520
- 7
- 116
- 154
-
As far as I understand, it will cause problems if the process creating name semaphore is crashed or exited without calling sem_unlink. Is the name semaphore existed until you reboot the system? – ken Apr 23 '13 at 15:32
-
Yes, you have to be careful to clean up. You can use a child process to do that. Basically, it uses a pipe to know when the parent exits and then unlinks the semaphore. It's a bit cumbersome, but not too hard. – Ken Thomases Apr 23 '13 at 23:04