Linux IO – Reading File During Write on Linux

iolinuxlocks

As I understand, when a file is being written, the process writing to the file obtains an exclusive lock. So other processes cannot access this file for read.

With the above knowledge, I'm unable to understand how I'm able to play a video in media player, when the browser is still downloading it.

Best Answer

Your understanding is wrong. Several Linux processes can write to the same file at once (and what happens then might be unspecified, except when the processes overwrite different segments of that file). And some other Linux process (e.g. your browser) can read a file which is written to.

You could adopt a convention to avoid that. For example, you could use advisory file locking (adopting the convention that every relevant program should do that), e.g. with flock(2), lockf(3), etc.... But that won't forbid other processes (not following your conventions) to access (or even write to) that file. You might use permission machinery (e.g. by dedicating a system user to your setuid program).

See also this & that answers on StackOverflow (some of them mentioned the deprecated mandatory locking Linux-specific mechanisms). Read about ACID properties, consider using some database (sqlite, PostGreSQL, MongoDB, etc...) or some indexed file (gdbm).

I don't know Windows, but heard the rumor that it does not allow concurrent access or writes to the same file.

Related Topic