multiple threads able to get flock at the same time

flock(2) is documented as “blocking if an incompatible lock is held by another process” and with “locks created by flock() are associated with an open file table entry”, so it should be expected that flock-ed locks by several threads of the same process don’t interact. (the flock documentation doesn’t mention threads). Hence, the solution should … Read more

flock(): removing locked file without race condition?

Sorry if I reply to a dead question: After locking the file, open another copy of it, fstat both copies and check the inode number, like 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 the … Read more

What is the best way to ensure only one instance of a Bash script is running? [duplicate]

Advisory locking has been used for ages and it can be used in bash scripts. I prefer simple flock (from util-linux[-ng]) over lockfile (from procmail). And always remember about a trap on exit (sigspec == EXIT or 0, trapping specific signals is superfluous) in those scripts. In 2009 I released my lockable script boilerplate (originally … Read more