in reply to Clearing out the file

The Camel (3rd Edition) has a very excellent discussion on file locking in Chapter 16 - Interprocess Communication. One particular paragraph from that discussion appears to directly answer your question.

I quote:

"To get an exclusive lock, typically used for writing, you have to be more careful. You cannot use a regular open for this; if you use an open mode of <, it will fail on files that don't exist yet, and if you use >, it will clobber any files that do. Instead, use sysopen on the file so it can be locked before getting overwritten. Once you've safely opened the file for writing but haven't yet touched it, successfully acquire the exclusive lock and only then truncate the file. Now you may overwrite it with the new data."
use Fcntl qw(:DEFAULT :flock); sysopen(FH, "filename", O_WRONLY | O_CREAT) or die "can't open filename: $!"; flock(FH, LOCK_EX) or die "can't lock filename: $!"; truncate(FH, 0) or die "can't truncate filename: $!"; # now write to FH

Cheers,
Darren