in reply to Atomic operation

This is exactly the situation where flock makes sense. But I think you need LOCK_EX. EX stands for "exclusive" while SH stands for "shared". If you had lots of data to read before the write it might make sense to first use LOCK_SH (prevents others to get LOCK_EX, but doesn't prevent the LOCK_SH of other readers). But since you do a quick test+optional write, LOCK_SH probably wastes more time than it saves on simultaneous reads.

So my advice: Just do your operation between a LOCK_EX and a LOCK_UN.

Linux and most other unixes work with flock, but you should avoid nfs-mounted partitions. It is probably best to include a test in your code if you anticipate the program to use different OSes

UPDATE: the seek in your example code seeks to the end of the file. Not a good idea if you want to read it or rewrite it, only good for appending.

Replies are listed 'Best First'.
Re^2: Atomic operation
by ikegami (Patriarch) on Jul 20, 2009 at 17:56 UTC
    Works fine in Windows too.
      I believe the semantics on Windows differ slightly from *nix. (On Unix locks are advisory, on Windows they are mandatory.) Also the semantics on *nix vary based on the filesystem. (NFS is different than remote Windows is different from local filesystem.)

      Which underscores the importance of having a unit test.

        on Windows they are mandatory

        hum, I was sure Windows had both kinds, but I can't find anything on advisory locks.

        flock creates mandatory locks on Windows. I did not know that.