views:

238

answers:

3

Hello, If one of my processes open a file, let's say for reading only, does the O.S guarantee that no other process will write on it as I'm reading, maybe leaving the reading process with first part of the old file version, and second part of the newer file version, making data integrity questionable?

I am not talking about pipes which have no seek, but on regular files, with seek option (at least when opened with only one process).

+2  A: 

No, if you open a file, other processes can write to it, unless you use a lock.

On Linux, you can add an advisory lock on a file with:

#include <sys/file.h>

...

flock(file_descriptor,LOCK_EX); // apply an advisory exclusive lock
Zifre
Advisory locks are not useful unless the writing application also agrees to use them.
Brandon Craig Rhodes
Advisory locks are sufficient if you are assured that every party involved is heeding them. Also, be aware of potential deadlock issues if one process blocks while waiting for a lock to be released.
jiggy
Mandatory locks are not always possible. For example, you may have to run mount with "-o mand" and change some flags on the file.
Zifre
+3  A: 

No, other processes can change the file contents as you are reading it. Try running "man fcntl" and ignore the section on "advisory" locks; those are "optional" locks that processes only have to pay attention to if they want. Instead, look for the (alas, non-POSIX) "mandatory" locks. Those are the ones that will protect you from other programs. Try a read lock.

Brandon Craig Rhodes
Mandatory locks are not a desirable feature, in my opinion :)
MarkR
Agreed! A better application design would be preferable. But, if he's got to protect a file against readers he can't control, they're they only way to go.
Brandon Craig Rhodes
A: 

Any process which can open the file for writing, may write to it. Writes can happen concurrently with your own writes, resulting in (potentially) indeterminate states.

It is your responsibility as an application writer to ensure that Bad Things don't happen. In my opinion mandatory locking is not a good idea.

A better idea is not to grant write access to processes which you don't want to write to the file.

If several processes open a file, they will have independent file pointers, so they can seek() and not affect one another.

If a file is opened by a threaded program (or a task which shares its file descriptors with another, more generally), the file pointer is also shared, so you need to use another method to access the file to avoid race conditions causing chaos - normally pread, pwrite, or the scatter/gather functions readv and writev.

MarkR