chrisvarnz
chrisvarnz

Reputation: 457

Cross-process locking with Android NDK?

Is there a way to lock e.g. using mutexes or file locks on Android NDK, across processes?

I want to lock a socket so only one process can send to it at once. The processes are not forked, they are independent invocations.

As I am writing a shared library, I cannot rely on any shared location which requires permissions to write to it, neither can I use any process local storage, because this would be unable to share with other processes by definition. This goes for app names too. I'm essentially looking for something like abstract namespaces with AF_UNIX sockets, but for mutex/semaphores.

Upvotes: 2

Views: 3238

Answers (1)

fadden
fadden

Reputation: 52323

Assuming the processes have the same user ID, you can use flock(2) to lock a file (could be anything accessible to both processes), or the POSIX semaphore operations (sem_open(3)) to use a semaphore.

If the user IDs are different, the mechanisms will still work, but you have to set the file permissions to be more "open" -- which introduces the risk of some malicious app performing a denial-of-service attack by grabbing the lock.

Upvotes: 3

Related Questions