in reply to Re: flock() ..I really need a hand .. please :)
in thread flock() ..I really need a hand .. please :)
I think what I was doing was concentrating so hard on KM's example of renaming the "locked file" the same name as the file getting written to, that I neglected to think of the first lesson I learned about flock(). That flock() works if the file in question shares the same locking functions throughout the code.
What I think I'm doing wrong, and please correct me if I'm not right, but when I was reading file A to spit out the contents, I was using a shared lock (LOCK_SH) and I named my $SEMAPHORE file the same name as file A but with .lck at the end. So sometime during the code I had to write to my TEMP file B and named my $SEMAPHORE file "file B.lck" So in essence the two $SEMAPHORE file names were different.
Is this were my mistake lays? If I'm assuming correctly I have to name my TEMP $SEMAPHORE file name the same as "file A" Does this make sense so far? I hope I'm explaining myself correctly :) Here is a small example of what I was doing wrong I think:
So am I safe to assume that this would wipe my file contents? Because when one process opened my main file for reading my other process may have been re-writing the TEMP file then renaming it, and my main file was not flocked. I think I'm confusing myself :/ but I hope I'm right.??!########################################## # Reading $Afile = "A.txt"; $SEMAPHORE = $Afile . '.lck'; open(S, ">$SEMAPHORE") or die "$SEMAPHORE: $!"; flock(S, LOCK_SH) or die "flock() failed for $SEMAPHORE: $!"; open (FH, "$Afile") or die "Can't open $Afile: $!"; while (<FH>) { ## do_something; } close FH; close S; ##########################################- wrong way # Writing $Bfile = "B.txt"; $SEMAPHORE = $Bfile . '.lck'; ### Using $Bfile as $SEMAPHORE file name open(S, ">$SEMAPHORE") or die "$SEMAPHORE: $!"; flock(S, LOCK_EX) or die "flock() failed for $SEMAPHORE: $!"; open (TEMP, ">$Bfile") or die "Can't open $Bfile: $!"; open (FH, "$Afile") or die "Can't open $Afile: $!"; while (<FH>) { ## do_something; } close FH; close TEMP; rename($Bfile,$Afile); close S; ########################################## -right way? # Writing $Bfile = "B.txt"; $SEMAPHORE = $Afile . '.lck'; ### Should be using $Afile as $SEMAPHORE + file name etc..
Thank you again, and thanks AgentM for the reply too. I'll give that module a try :-)
|
|---|