- 论坛徽章:
- 0
|
8. How do I create a lock file?
Very carefully 
The scheduler can stop one process in the middle of a non-atomic
operation, and run another one, which wants to perform the same
operation. The second one, having a full timeslice, might finish
the operation. When control returns to the first process, confusion
will reign.
The trick is to do something atomic, so that this won't
happen. There are a couple ways to do this. One is to create a
directory instead of a file, the other is to create a symbolic
link. Both operations are defined to be atomic by POSIX/SUS, by
virtue of the fact that they both require invocation of the
corresponding system calls, which are atomic.
Beware of trying to create ANY kind of lock file on an NFS
partition. NFS pretty much eliminates anything like atomicity. If
you're going to create a lock file, make sure you're doing it on a
local partition, such as /tmp.
Netscape/Mozilla uses the symbolic link method for its lockfile (in
spite of the fact that it creates it in the user's home directory,
which may be NFS mounted). When it starts up it creates a file
named for the IP address of the machine it's running on, and the
pid of the creating process. Then it tries to create a symbolic
link named "lock", which points to that file. If this symlink
already exists, link(2) will return an error. In a script this
would work something like
touch /tmp/xxx
ln -s /tmp/xxx /tmp/lockfile 2>/dev/null
ret=$?
rm /tmp/xxx
if [ $ret -ne 0 ];then
echo lockfile already exists
exit 1
else
echo success
fi
If you have procmail installed, another possibility is the
lockfile(1) command that comes with it. |
|