> 
> open(FILE,">$datafile");
> flock(FILE, LOCK_EX);
> print FILE "$input\n";
> close(FILE);
> 
> Notice that I do not use flock(FILE, LOCK_UN); before I close 
> the file. I
> don't use it because I was told not to by the server administrator.

The file is implicitly unlocked when you close the file, it's a perl thing
not an OS thing so it works on windows too.  I have several scripts running
on W2K servers that use flock and I haven't had any surprises.  

One thing about the above code though, you are truncating the file before
you know if it's locked.  This might not make other apps using the same file
happy. Take a look at perldoc perlopentut.

...  

To get an exclusive lock, typically used for writing, you have to be
careful. We sysopen the file so it can be locked before it gets emptied. You
can get a nonblocking version using LOCK_EX | LOCK_NB.

    use 5.004;
    use Fcntl qw(:DEFAULT :flock);
    sysopen(FH, "filename", O_WRONLY | O_CREAT)
        or die "can't open filename: $!";
    flock(FH, LOCK_EX)
        or die "can't lock filename: $!";
    truncate(FH, 0)
        or die "can't truncate filename: $!";
    # now write to FH 

Reply via email to