The Lock File Technique

The lock file technique is a coarse-grained locking technique, since it implies that the entire file is locked. The technique is simple, however:

  1. Attempt to create and open the lock file.

  2. If step 1 fails, sleep for a while and repeat step 1.

  3. If step 1 succeeds, then you have successfully locked the resource.

The success of this method depends on the fact that the creation and opening of the lock file must be atomic. In other words, they must either succeed completely or fail completely.

This is easily accomplished with the UNIX open(2) call, when the options O_CREAT|O_EXCL are used together:

fd = open("file.lck",O_WRONLY|O_CREAT|O_EXCL,mode);

The O_CREAT flag tells open(2) to create the file if it does not exist. However, ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.