File Locking
Webmin version 0.81 introduced several new common functions for locking files to prevent multiple programs from writing to them at the same time. Module programmers should make use of these functions in order to prevent the corruption or overwriting of configuration files in cases where two users are using the same module at the same time.Locking is done by the function lock_file, which takes the name of a file as a parameter and obtains and exclusive lock on that file by creating a file with the same name but with .lock appended. Similarly, the function unlock_file removes the lock on the file given as a parameter. Because the .lock file stores the PID of the process that locked the file, any locks a CGI program holds will be automatically released when it exits. However, it is recommended that locks be properly released by calling unlock_file or unlock_all_files before exiting.
The following code shows how the locking functions might be used :
&lock_file("/etc/something.conf");
open(CONF, ">>/etc/something.conf");
print CONF "some new directive\n";
close(CONF);
&unlock_file("/etc/something.conf");
Locking should be done as soon as possible in the CGI program, ideally before
reading the file to be changed and definately before writing to it. Files can
and should be locked during creation and deletion as well, as should
directories and symbolic links before creation or removal. While this is
not really necessary to prevent file corruption, it does make the logging of
file changes performed by the program more complete, as explained below. Many other programs also use .lock files for the same purpose, but most do not put their process ID in the file. If the lock_file function encounters a lock like this, it will wait until it is completely removed before obtaining its own lock, as there is no way to tell if the original process is still running or not.
