in reply to Trying to understand flock

flock implements advisory locking, which means that other applications are free to ignore the lock. The Windows emulation of flock uses mandatory locking, which means that other applications cannot ignore the lock.

Here's one way of doing the same without the extra file:

use strict; use Fcntl qw( LOCK_EX SEEK_SET ); my $file = 'data.file'; open(my $FH, '>>', $file) or die("Can't open $file: $!\n"); flock($FH, LOCK_EX); seek($FH, SEEK_SET, 0); truncate($FH, 0); ...

Replies are listed 'Best First'.
Re^2: Trying to understand flock
by toniax (Scribe) on Nov 14, 2010 at 22:26 UTC
    Hi,
    Thanks for the code.
    I had a question about that code.
    I do not understand why you would want to truncate the file you are trying to append to ? I also do not understand why
    you would use seek . I am really getting confused
    I know its just an example. I am just wondering the reasoning behind it?
      We want to clobber the file, but we don't want to clobber the file until we've locked it. The catch is that one can't lock a file one doesn't have open, so we can't use open ">" to clobber the file. That means we have to start by opening the file without clobbering it (e.g. by using open ">>") and by locking it. Then, we're free to clobber it.
        Thanks for the explanation. I understand now.
      i stay away from file locking as much as possible. for the most part it is advisory locking, so you need to write programs that use flock and read/write clode blocks in an atomic way that prevents race conditions or lockup. there's specific ways you are meant to write perl code when using flock, to avoid said lockups..and the code sometimes looks like the martians have landed. the flock perldoc has some of the gory details. Even with all the contrived code, the possibility of deadlock is still real, and hence it's probably better to avoid the situation altogether.
      i'm sure some of the higher order perlmonks have memorised the particular idioms/code to use, and can write pretty stable code to share a file. personally i don't think it's best practice to share a file via a locking mechanism.
      the hardest line to type correctly is: stty erase ^H