Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two processes opening the same file for writing

What will happen when two processes open a non-existent file for writing at the same time? i.e. Consider this C++ code that's run in two concurrent processes

ofstream ofs("/my/test/path/some_file")

Will the OS serialize the actual file creation?

PS: I'm coding on Windows, so I'm primarily interested in seeing what Windows will do, but I'm curious to know if the behavior here is os dependent.

like image 369
DigitalEye Avatar asked Sep 19 '14 00:09

DigitalEye


Video Answer


1 Answers

There's nothing particularly exciting about two processes opening the same file for writing.

The fun part starts when those processes try to both write to the same file. The OS is not going to play a referee. Each individual process is going to get scheduled by the OS to execute when the OS feels like it. Whatever the process does during its time slice, the OS will generally stay out of its way. One process may write something to the file, then the other process might write something, or might not. Depending on what the code does.

So, unless explicit steps are taken, in some way, for multiple processes to coordinate their access to the file, the end result of multiple processes writing to a file cannot be predicted. The computer is not going to catch fire or implode, the world will not come to an end. But, every time this experiment gets repeated, the results will be different.

like image 146
Sam Varshavchik Avatar answered Oct 25 '22 09:10

Sam Varshavchik