gri6507 has asked for the wisdom of the Perl Monks concerning the following question:

Fellow monks,

This must be easy, but my brain is too tired to think of it. I have the following code

open(LOG,">>$logfile") || die "error opening $logfile for append: $!\n +";

When I run my program from the first terminal, it opens the file for append as expected (I can tell because of later prints to LOG). However, when I start another instance of the same program from a different window, I don't get the error message. How can two instances of perl have the same file open for exclusive append? What am I missing?

Replies are listed 'Best First'.
Re: Exclusive open for append
by Aristotle (Chancellor) on Nov 18, 2005 at 16:13 UTC

    Where do you see the “exclusive” part? You didn’t flock the file, after all.

    Makeshifts last the longest.

      D'oh. All I needed was flock(LOG, LOCK_EX | LOCK_NB) || die "cannot lock $logfile: $!\n";. Thanks.
Re: Exclusive open for append
by jeffa (Bishop) on Nov 18, 2005 at 16:15 UTC

    Check out perldoc -f sysopen:

    In many systems the "O_EXCL" flag is available for opening files in exclusive mode. This is not locking: exclusiveness means here that if the file already exists, sysopen() fails.
    You probably should be locking the file. See perldoc -f flock

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Exclusive open for append
by Perl Mouse (Chaplain) on Nov 18, 2005 at 16:16 UTC
    There's no such thing as an "exclusive append".

    Both programs will have the file open for append. If both programs write to them, there's no garantee you end up with something that isn't garbage - some OSses will do a seek() before a write(), and a flush() after a write(), if your writes() are small enough, the messages won't be garbled.

    If you want to have exclusive access, flock() your handles.

    Perl --((8:>*
      Both programs will have the file open for append. If both programs write to them, there's no garantee you end up with something that isn't garbage...

      On sane Unix-like systems, there is a guarantee: you won't get garbage, regardless of the size of your writes. [1] If the log file is opened in append mode and each entry is committed as a single write (system call), Unix file semantics guarantee that the entries will be appended to the file atomically. (For more information see Re^3: Looking for a simple multiprocess-enabled logging module, which quotes the relevant bits of the Single Unix Specification.)

      See also "All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?" from perlfaq5.

      Cheers,
      Tom

      [1] Provided that your log file resides on a filesystem that supports Unix semantics. Network-mounted filesystems often fall short.