Prev

Perl Notes

Next

Chapter 8.3 Exclusive Access to a File

It's a good idea to flock a file before writing to it. This ensures that multiple processes won't try to write to it simultaneoudly, possibly damaging or garbling the file's contents.

To get exclusive access to a file:

  1. After opening the file, type flock(LABEL, where LABEL is the filehandle for the file.
  2. Type , 2). The 2 indicates that you want exclusive access to a file.
  3. Type ; to complete the line.

To release exclusive access to a file:

  1. Type flock(LABEL, where LABEL is the filehandle for the file.
  2. Type , 8). The 8 indicates that you wish to release the file.
  3. Type ; to complete the line.

open(FILE, ">>../myfile.txt") || &ErrorMessage;
flock(FILE, 2);
print FILE "I'm adding text to a file.\n";
flock(FILE, 8);
close(FILE);

sub ErrorMessage {
  print "Could not open file. It either does not exist or the permissions are wrong\n";
  exit;
}


Prev Home Next