I would like to prevent a script from launching twice by using a PID file. There are many ways to implement exclusivity, but since my script will always run on a Linux machine and I would like to be able to detect stale PID files automatically, I would like to use flock(2)
to implement this.
I was told long ago by a colleague that the following pseudocode is the right way to do this (open(..., 'w')
means "open in write mode with O_CREAT
"):
fd = open(lockfile, 'w');
write(fd, pid);
close(fd);
fd = open(lockfile);
flock(fd)
file_pid = read(fd)
if file_pid != pid:
exit(1)
// do things
I am curious why he suggested the above instead of:
fd = open(lockfile, 'w')
flock(fd)
// do things
Presumably he suggested this because he thought the "create file if it doesn't exist" functionality of open(2)
with O_CREAT
is not atomic, that is, two processes who call open(2)
at exactly the same time might get handles to two different files because the file creation is not exclusive.
My question is, is the latter code always correct on a Linux system, or if not, when is it not correct?