open (FLAG, '<', "flagfile") or die "cannot open flag $!"; flock FLAG, LOCK_EX or die "cannot lock file! $!"; #mode 2 # you have an exclusive lock to FLAG here.. # by cooperation convention, I that means I have exclusive # access to both the LOG file and the TEMP file # other processes don't update or use either open (LOG, '<', $file) or die "cannot open $file $!"; open (TEMP, '>', "tempName") or die "cannot open tempName $!"; # there will only be one "tempfile" at a time, so the name # doesn't matter much. Add your program name into it so that it is # unique amongst other processes and I think that's all you need # i.e. no rand() required. while () { # process each line in LOG print TEMP "whatever"; } close LOG; # this would release the lock # but we are using a different lock # for IPC coordination. unlink $file; # I think necessary for the rename of the temp # file to the log file's name. close TEMP; rename "tempName", "$file"; # "LOG" replaced with # the edited version close FLAG; #releases lock.