45.36 Shell LockfileHere's an efficient and portable way to create a lockfile from a shell script. [6] It's also an interesting demonstration of the way that UNIX umasks (22.4 ) and file permissions (22.2 ) are handled.
A lockfile can be used if a particular program might be run more than once at the same time - and you need to be sure that only one instance of the program can do something (like modify some file, access a printer, etc.). Let's say you have a script called edmaster ; it edits a master configuration file named config . To be sure that two users can't modify the config file at the same time, the first edmaster would check whether the lockfile exists. If the lockfile doesn't exist, edmaster will create it and modify the config file. When it's done editing, it removes the lockfile. If someone tries to run a second edmaster process, it will see the lockfile from the first edmaster , wait and check every few seconds to see if the lockfile is gone. Once the first edmaster removes the lockfile, the second edmaster can create the lockfile and do its editing of config . Here are pieces of a script that check the lock, create it, and (later) remove it:
So if another user tried to run edconfig , and jpeek had run edconfig first, she might see: %
How does it work?
Almost all of the action is in the first line of the loop.
A umask of 222 creates files that are read-only
(mode If the lockfile already exists (because another process has created it),
the loop executes But, if the lockfile is read-only, how can it ever be created? That's the other interesting part of this technique. The umask only applies to the file as it's created; if the file doesn't exist, the umask doesn't apply to it (yet) and the file can be created. In fact, you can create a file with mode 000 by typing: $ - |
|