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.