c - flock(): removing locked file without race condition? -


i'm using flock() inter-process named mutexes (i.e. process can decide hold lock on "some_name", implemented locking file named "some_name" in temp directory:

lockfile = "/tmp/some_name.lock"; fd = open(lockfile, o_creat); flock(fd, lock_ex);  do_something();  unlink(lockfile); flock(fd, lock_un); 

the lock file should removed @ point, avoid filling temp directory hundreds of files.

however, there obvious race condition in code; example processes a, b , c:

a opens file locks file b opens file unlinks file unlocks file b locks file (b holds lock on deleted file) c opens file (a new file 1 created) c locks file (two processes hold same named mutex !) 

is there way remove lock file @ point without introducing race condition ?

sorry if reply dead question:

after locking file, open copy of it, fstat both copies , check inode number, this:

lockfile = "/tmp/some_name.lock";      while(1) {         fd = open(lockfile, o_creat);         flock(fd, lock_ex);          fstat(fd, &st0);         stat(lockfile, &st1);         if(st0.st_ino == st1.st_ino) break;          close(fd);     }      do_something();      unlink(lockfile);     flock(fd, lock_un); 

this prevents race condition, because if program holds lock on file still on file system, every other program has leftover file have wrong inode number.

i proved in state-machine model, using following properties:

if p_i has descriptor locked on filesystem no other process in critical section.

if p_i after stat right inode or in critical section has descriptor locked on filesystem.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -