in reply to Vexing Race Condition

As ikegami points out, the file open truncates the file before you have a chance to lock it.

A common solution is to use a different file for the cooperative locking. Make a file, "lockfile_logx" and get and release locks on that file's file handle to protect all of the operations on $file.

Replies are listed 'Best First'.
Re^2: Vexing Race Condition
by tybalt89 (Monsignor) on May 02, 2025 at 21:42 UTC

    Or use Path::Tiny's trick: open the file for append, lock it, truncate to 0, then write new data :)

    ( Untested, let me know if it works :)

      Actually Path:Tiny's trick is renaming a temporary file. My idea of opening read-write, locking then truncating turns out to be a non starter as mode +> clobbers the file and mode +< fails if the file doesn't already exist, I was able to run the script with no errors after touching the file although in the wild that would be another race condition. Opening the file in append mode as you suggest does work, so it's an option although using rename is probably more robust as it will also work for processes that don't use flock.

        Check out Path::Tiny::append with the truncate option. Path::Tiny has more than one trick up its sleeve.

Re^2: Vexing Race Condition
by Maelstrom (Beadle) on May 03, 2025 at 13:29 UTC
    It was my understanding that using a different file was referred to as a semaphore lock. I'm less sure after googling the term but I'm sure I've seen people refer to a 'semaphore file'.