in reply to Atomic update counter in a file

This one still has a race condition between the test for existance and the creation of the new file.

Which is why typically you never perform that test -- its redundant and introduces a race condition

Replies are listed 'Best First'.
Re^2: Atomic update counter in a file
by Anonymous Monk on Nov 18, 2015 at 10:37 UTC
    Then what do you suggest to atomically differentiate between creation of the file and update of the file?
      Answering my own question... This seems to do the trick:
      use Path::Tiny;
      #... some perl stuff
      my $FH = path(".counter")->filehandle({locked=>1, exclusive=>1}, "+>>", ":raw") or die("open .counter: $!\n");
      seek($FH,0,0);
      my $nr; { local $/; $nr = <$FH> };
      $nr ||= "000\n";
      die("garbage in .counter\n")  unless $nr =~ /^\d+\n$/;
      chomp($nr);
      ++$nr;
      truncate($FH,0);
      seek($FH,0,0);
      print $FH $nr, "\n";
      close($FH) or die("close .counter: $!\n");
      # and continuing using $nr
      
      The mode "+>>" creates the file when it does not exist yet, and allows for read and write. The "locked" and "exclusive" mode make sure we're the only one using it.