Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c/c++ flock as mutex on linux not robust to file delete

Tags:

c

linux

File locking in C using flock is commonly used to implement cross-platform cooperative inter-process locking/mutex.

I have an implementation (mac/linux/win) that works well, but it is not robust to file deletion (at least under Linux).

One or more process have started creating and using lockfile (/tmp/lockfile) and cooperatively interlock on a shared resource with it.

Some time later, I manually delete the lockfile (rm /tmp/lockfile). The running process keep on cooperating with each other, but any new process that wants to start using the same resource lock and lockfile breaks the overall mutex logic. It will create a new version of the /tmp/lockfile that is somehow different to the one already in used in already running process.

What can be done to prevent the lockfile from being unlinked while any process has it open? What other solutions can be used?

I can't use a semaphore because I need the lock to self-release if the owning process crashes.

like image 570
Michel Sanches Avatar asked Jan 18 '26 20:01

Michel Sanches


1 Answers

You can indeed use a semaphore. Linux provides the flag SEM_UNDO, which will undo the semaphore-operation on process termination (see semop(2)).

like image 170
Ctx Avatar answered Jan 20 '26 11:01

Ctx