Locking a File With the Perl Flock Function

Many CGI programs, such as guestbook programs, require that only one user at a time be allowed to access a data file. You can lock a file with the Perl flock function (flock stands for file lock). You use it with a filehandle like so:

 open (FILE, "data.txt");flock (FILE, 2);

The file is now locked, and no one else can write to it until it is unlocked. It’s possible to explicitly unlock the file with flock, but it’s cleaner to let the system unlock the file when the filehandle is closed. Closing the file will unlock it and also flush the buffer.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: