views:

22

answers:

1

I'm curious what happens in this scenero. Suppose I open a file for reading, and begin reading the contents in a loop. Like this:

$fp = fopen('test.txt', 'r');
while(!feof($fp)) {
    fread($fp, 1024);
}
fclose($fp);

What happens if another process starts appending to the file while I'm reading it?

+1  A: 

On UNIX/Linux:

All processes just see the file as a bunch of bytes with a length. If someone else changes the bytes or changes the length, all other processes immediately see this new data.

An open file refers to an inode. If you create a completely new file then it's a new inode. If you rename the new file over the old file, the filename in the directory now references the new inode, whereas you have the old inode open (even though it can now no longer be seen as it's not linked anywhere from any directory.) In this case, you continue to see the old file and any process opening/modifying the new file sees only the new file.

Adrian Smith
So the process running the code above doesn't some how get it's own copy of the file from the OS while it's being read? The code above could loop forever if other processes are constantly appending to the file?
mellowsoon
"he code above could loop forever if other processes are constantly appending to the file? " Yes. See tail -f which relies on this behaviour.
Paul