in reply to Re^2: Why can't some of my modules do log output to a file?
in thread Why can't some of my modules do log output to a file?

I'm wondering if it's efficient to open close the file each time, the handle could be kept in the closure. And flock would cover problems with concurrent use.

Opening and closing each time is indeed less efficient. Keeping the file open would require a lock-seek-write-flush-unlock sequence, which introduces more complexity, and given that the OP is debugging "weird" behavior, I thought it best to give the simpler, albeit less efficient, method that uses only simple filesystem operations. I perhaps should have clairifed that my suggestion is one for debugging and not for high-performance logging. (Also, I seem to remember that keeping the file open does not work on Windows when multiple processes are accessing it, though I'm not yet sure whether that's the case here.)

  • Comment on Re^3: Why can't some of my modules do log output to a file?

Replies are listed 'Best First'.
Re^4: Why can't some of my modules do log output to a file?
by Marshall (Canon) on Oct 10, 2022 at 21:57 UTC
    Instead of closing the file handle, you could just release the lock.  flock $fh, LOCK_UN or die "flock can't release lock $!";

    Note from the docs: "To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE before locking or unlocking it."
    So, lock, write, unlock will cause 2 flushes. There is no need to explicitly seek or flush.

      Instead of closing the file handle, you could just release the lock.

      That's what LanX and I both said.

      So, lock, write, unlock will cause 2 flushes.

      That's why I wrote "lock-seek-write-flush-unlock" and not "flock-seek-print-flock", because I was referring to the underlying operations.

      There is no need to explicitly seek

      That is very wrong unless you know for sure that O_APPEND semantics are guaranteed. For example, if the file was opened with '+<' instead of >> or on NFS filesystems, you definitely need the seek or you will corrupt your data.