Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Typically on Linux, unless you're using locking of some kind, two processes can quite happily have the same file open at once, even for writing. There are three ways of avoiding problems with this:</p> <ol> <li><p><strong>Locking</strong></p> <p>By having the writer apply a lock to the file, it is possible to prevent the reader from reading the file partially. However, most locks are advisory so it is still entirely possible to see partial results anyway. (Mandatory locks exist, but a strongly <em>not</em> recommended on the grounds that they're far too fragile.) It's relatively difficult to write correct locking code, and it is normal to delegate such tasks to a specialist library (i.e., to a database engine!) In particular, you don't want to use locking on networked filesystems; it's a source of colossal trouble when it works and can often go thoroughly wrong.</p></li> <li><p><strong>Convention</strong></p> <p>A file can instead be created in the same directory with another name that you don't automatically look for on the reading side (e.g., <code>.foobar.txt.tmp</code>) and then renamed atomically to the right name (e.g., <code>foobar.txt</code>) once the writing is done. This can work quite well, so long as you take care to deal with the possibility of previous runs failing to correctly write the file. If there should only ever be one writer at a time, this is fairly simple to implement.</p></li> <li><p><strong>Not Worrying About It</strong></p> <p>The most common type of file that is frequently written is a log file. These can be easily written in such a way that information is strictly only ever appended to the file, so any reader can safely look at the beginning of the file without having to worry about anything changing under its feet. This works very well in practice.</p></li> </ol> <p>There's nothing special about Python in any of this. All programs running on Linux have the same issues.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload