Lock Files

By Danny Kalev, ITworld |  How-to

Locking a Shared File
A file that can be updated by multiple processes must be locked to
ensure that only a single process can update it at any given time. Lock
files are a simple locking technique that associates a data file with
another file serving as a lock. When the lock file exists, its
associated data file is considered locked and other processes are not
allowed to access it. If the lock file doesn't exist, a process that
wishes to update the data file first creates a lock file and then
updates the data file. When the file updating is completed, that
process deletes the lock file.

Implementation
Suppose we want to modify the configuration file config.cfg, which
several users may access. Before accessing it, we try to create a lock
as follows:

int fd=open("config.lck", O_WRONLY | O_CREAT | O_EXCL, 0644)

Writing the current pid into the lock file is customary so that other
processes can tell who's holding the lock. The O_CREAT flag indicates
that, if the file doesn't exist, then open() will create it. The O_EXCL
flag ensures that the open() call is atomic. If the file already
exists, open() will fail and set errno to EEXIST. This way you
guarantee that only a single process at a time can hold the lock. The
return status of the open() call is checked as follows:

if (fd<0 && errno==EEXIST)
{
printf("the file is currently locked; try again later");
return -1;
}
else if (fd < 0)
{
printf("an unknown error has occurred");
return -1;
}
/* if we got here, we own the lock*/
write(fd, getpid(), sizeof(pid_t));
return 0;

Once a process owns the lock, it can update the data file safely. Upon
completion, the said process deletes the lock as follows:

unlink("config.lck");

At this moment, the data file is considered unlocked and another
process may access it.

Limitations of Lock Files
This technique isn't bulletproof; if a process doesn't check the lock
before trying to open the data file, multiple processes might update
the file simultaneously. Another problem might occur if a process that
is currently holding the lock is aborted before releasing it. In this
case, the data file remains locked. If the pid stored in the lock file
belongs to a process that is no longer active, you can assume that the
file isn't really locked. However, if another process has received the
same pid in the meantime, the data file will remain locked.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question