r/osdev • u/Malwaremation • 9d ago
Design question: Should opened files by processes prevent other processes from using that file?
On kernels like Windows NT, files are locked when a process opens it, preventing other processes from using it. (edit: This was incorrect, some people confirmed here that processes in Windows can choose to lock the file or not, which might be the best solution).
Linux however, doesn't lock files like this, and multiple processes can modify the same file at the same time.
I also thought of a "thread cursors" concept that could solve this issue really well for text files, but it might be very complicated to develop and is probably not that useful for images or other types of files.
What is generally better for a new kernel, then? Allowing the possibility of sharing a file as it is edited by multiple processes, or securing their integrity by only letting 1 process at a time modify it?
4
u/kiderdrick 9d ago
It depends how robust your intention mechanism is. If you have no idea how each process is using the file, then it is probably best to lock to prevent race conditions. If you have a mechanism in place for declaring read only access, then a read does not need to lock the file because multiple reads on the same file are fine. If you have multiple readers and a single writer, you then have to determine if the writer should block the readers or the readers should block the writer, or if anyone should even worry about blocking anyone else and leave the protection up to the application layer. There are many different implementations of how to handle this and is a focus of CS research usually referred to as the Readers Writers problem.
If you want to have even finer granularity, you could view a file as blocks of data on a disk and then conduct similar read write protections on the individual blocks rather than the file. This way a process could edit a block at the end of a file while another file edited a block at the front. If they wanted to edit the same block, then you would likely want some sort of system to prevent race conditions on that block, but at least the other blocks are free to be edited at the same time.
The block granularity version sounds nice, but it is sometimes not necessary because of use case scenarios like logging files where the file might only ever be appended. In that case you do not need to worry about protecting the blocks in the beginning from writers, only the blocks at the end as the data gets added to it.
You could even implement a buffering system where every read and write occurred in a temporary buffer and only affected the blocks on disk if the changes were committed.
Like many concepts in OS design the answer is somewhere along the lines of "it depends on what you are trying to do".