O'Reilly logo

Advanced UNIX Programming by Warren W. Gay

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required