Usually another process could move the file mid-write, which will cause the first process to create a new file or crash, depending on how it's written.
It's a good idea to use a mutex (mutual exclusion) file when this is a concern, or temp files and symlinks, depending on your specific setup. A mutex is a file that is written, who's mere existence tells other programs that you're accessing some shared file. Your first process checks for the existence of a mutex file, if one is there it waits, otherwise it writes its own. It then does whatever it needs to on the shared file, finishes up, and finally it deletes its mutex to tell all other processes that the shared file is available for modification.
A variation on the mutex idea is for the writing code to create a small "finished" or "done" file when the writing is complete. Any other process should then ignore the file of interest (call it "file"), until the "done" file appears (call it "file.done"), indicating that "file" has finished writing.
A setup with temp files and symlinks is a little more complicated, but can be very useful if you have one process periodically writing to a file, and another process reading from it, but you only want to read from it if the file is complete. In that case your "file" would be a symlink, that would either point to "fileA" or "fileB". The writing process would check the target of the symlink, and then write to the OTHER file (so if "file" points to "fileA", the writing process would write to "fileB"). When the writing is complete, the writing process moves the symlink target from "fileA" to "fileB". The reading process can then just read from "file", without regard for which target "file" is actually pointing to.
Last edited by suicidaleggroll; 02-23-2012 at 01:04 PM.
|