No, you've got a destruction going on. Consider:
- process 1 opens for create - file deleted
- process 1 flocks - and continues
- process 1 writes its data
- process 2 opens for create - blam, process 1 data is gone
- process 1 closes, releasing the flock
- process 2 flocks - and continues
- process 2 writes its data
- process 2 closes
I guess if your goal is to have only the most recent data, you've succeeded, but you didn't need to do the flock for that... you can just leave the flocks entirely out.
| [reply] [Watch: Dir/Any] |
The problem merlyn is trying to point out is that when you open the file for writing (open (FH, ">file")), you already deleted the contents of the file regardless of any locks. From perlopentut:
To get an exclusive lock, typically used for writing, you have to be careful. We "sysopen" the file so it can be locked before it gets emptied. You can get a nonblocking version using "LOCK_EX | LOCK_NB".
use 5.004;
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
Hope that helps!
| [reply] [Watch: Dir/Any] [d/l] [select] |