Hi all,

I have a question about the way flock() and fclose() work in PHP.
Consider the following code, slightly modified from the flock() PHP
manual page:


$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
   fwrite($fp, "$processName\n");
   flock($fp, LOCK_UN); // release the lock
} else {
   echo "Couldn't lock the file !";
}
fclose($fp);


If the above code was executed by two processes, process A and process
B, one possible sequence of events is:

Process A opens the file.
Process B opens the file.
Process A obtains an exclusive lock.
Process A writes it's process name to the file.
Process A releases the exclusive lock.
Process A closes the file.
Process B obtains an exclusive lock.
Process B writes it's process name to the file.
Process B releases the exclusive lock.
Process B closes the file.

The results would be as desired - that is, as process B obtained the
lock on the file after process A, it is process B's process name that is
in the contents of the file, not process A.

However, another possible sequence of events is:

Process A opens the file.
Process B opens the file.
Process A obtains an exclusive lock.
Process A writes it's process name to the file.
Process A releases the exclusive lock.
Process B obtains an exclusive lock.
Process B writes it's process name to the file.
Process B releases the exclusive lock.
Process B closes the file.
Process A closes the file.

In this case, although process B is the second process to obtain a lock
and write its process name to the file, it is the first process to close
the file handle.

This raises the question of when the operating system actually writes
file contents to disk. Is it when PHP performs an fwrite()? Or does the
O/S buffer the file contents?

Essentially, when performing the style of concurrent programming above,
can one be certain at what point in time the file contents will be
written (on any operating system)?

My suspicion is that the answer to the above question is no, and as a
result, in order to be certain of correctly serialising the file locking
and output process, it would be necessary to use a separate lockfile,
which is opened and locked *before* the file to be written to is opened,
written, and then closed, after which the lock on the lockfile can be
released.

Can anyone please confirm that this is the case?

Thanks,

-- 
Andrew Hill
[EMAIL PROTECTED]

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to