14

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.

Sorter
  • 393

3 Answers3

15

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.

4

The files usually aren't locked - unix file locking. It is also fairly common to have multiple readers of file but only one writer. Problems only occur when you would have multiple writers.

Also, most videos file formats (and especially on the web) are streamable, which means that you don't have to have the whole video to play it.

matt.s
  • 181
  • 1
  • 6
3

Unix OSes do not use compulsory locking (Gnu/Linux is a Unix, other examples are UNIX, BSD, Mac OSX). Locking as avoided where ever possible.

Some other OSes use compulsory locking all the time (Notably Microsoft's Windows OS). This will stop you playing until fully downloaded, it will also stop you renaming a file or directory that is open (that an application is in). But on Unix it is OK. If an application needs locking it can use it. But not normally.