in reply to File locking

A short word to file locking

File locking works only for writing files. If you want to implement it for reading, you have to open the file as read/writeable. Then all other processes, which opens the file in read/write mode too, will wait until the first process unlocks the file.
For just reading the file, locking is not nessessary and wouldn't even work.

----------------------------------- --the good, the bad and the physi-- -----------------------------------

Replies are listed 'Best First'.
Re: Re: File locking
by chipmunk (Parson) on May 13, 2001 at 22:02 UTC
    I don't think this is correct in general. Here's an example that demonstrates locking a file that has been opened for reading:
    #!/usr/local/bin/perl -w use strict; use Fcntl qw/:flock/; my $file = 'flock.test'; -e $file or open(FILE, ">$file") or die "Can't create $file: $!"; if (fork) { open(FILE, "<$file") or die "Can't open $file for reading in paren +t: $!"; flock(FILE, LOCK_EX) or die "Can't flock $file in parent: $!"; wait; } else { sleep 1; open(FILE, "<$file") or die "Can't open $file for reading in child +: $!"; flock(FILE, LOCK_EX|LOCK_NB) or die "Can't flock $file in child: $ +!"; }
    And here's the output it produces when run on my system: Can't flock flock.test in child: Resource temporarily unavailable at flock.pl line 18. However, this behavior is probably system dependent, so physi and I are likely both right.
Re: Re: File locking
by virtualsue (Vicar) on May 13, 2001 at 22:42 UTC
    For just reading the file, locking is not nessessary and wouldn't even work.

    This is only true if the file is never going to be modified programmatically. If it is, then it needs to be flock'ed in shared mode (LOCK_SH) unless you don't care about the fact that the file might change while you're trying to read it. Usually you do care, 'cos if you don't then I don't see why you are bothering to lock it at all. ;)