56.4. 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 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 lock_file function, which takes the name of a file as a parameter and obtains an exclusive lock on that file by creating a file with the same name but with .lock appended. The unlock_file function also 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. It is recommended, however, 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
";
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 definitely before writing to it. Files can and should be locked during creation and deletion, 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.170.239