At 5:21 AM +0100 11/28/11, timothy adigun wrote:
 >
 > From: Owen <rc...@pcug.org.au>
 >
 > There is no race condition.
 >
 > And that code demo is correct


Actually, there is in a multitasking environment. Please, check subtitle
"File Locking" in perldoc perlopentut.

   masayoshi <rocksta...@y7mail.com> wrote:

 Before calling print method, the file might be deleted by another process
 So I reckoned when "File exists" appeared, the file might be deleted. >_>


I think what you want will be * flock * function. Check subtitle "File
Locking
under perldoc perlopentut,
Also check perldoc -f flock.

There is no race condition in the code that was posted originally (posters should remember to include the code on which they are commenting -- not everybody will be able to view the original message), because there is nothing done after the existence of the file is tested. The file exists or does not exist at the time the test is made, and the printed output is true for that time (and that time only).

A race condition would exist if the program assumed that the file's existence did not change after it was tested and acted upon that assumption unconditionally. For example, in the following:

if( -e $file ) {
  open(my $fh, '<', $file);
}else{
  open(my $fh,'>',$file);
}

two race conditions can occur: an existing file could be deleted by another process between the '-e $file' test and the open-for-reading, and a non-existent file could be created between the '-e' test and the open-for-writing.

That being the case, you should always test the return value of open if you care about whether a file exists or not. Since the '-e' test is redundant and possibly misleading, you may as well skip it if the existence of the file is a critical decision. If you need to guard against simultaneous access to the same file by two processes, then some file locking should be considered.

In most cases, there is little chance that another process will create or delete a file between two successive Perl statements. Only someone who is familiar with the specific situation can determine if that improbable event, which may occur eventually, is worth guarding against.

--
Jim Gibson
j...@gibson.org

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to