views:

134

answers:

2

On Linux pwrite operation (which is seek+write) is atomic, meaning doing pwrite-s in multiple threads with one file descriptor is safe. I want to create file descriptor duplicate, using dup(). Now, having fd1 and fd2 - will pwrite-s work as expected, or there's danger of race condition?

+4  A: 

File descriptor pairs created through dup share the same file status, (e.g. an lseek operation on one file descriptor will affect the other), because they refer to the same entry in the process open files table, which means they are essentially indistinguishable. The only thing they do not have in common is file descriptor flags, (e.g. FD_CLOEXEC.)

From the man page:

After a successful return from dup() or dup2(), the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.

Given that dup allows you to use the two file descriptors interchangeably, (because they refer to the same file in the process file table) I assume this implies that calling pwrite on one would be the same as calling it on the other, and thus be atomic.

Charles Salvia
I'm not sure i understand the answer. If there are 2 pwrites in 2 threads on duplicate file descriptors to different places in the file - is it OK?
Drakosha
Yes, it would be safe. It *wouldn't* be safe if you opened the same file with `open`. But if you use `dup` then the two file descriptors are basically indistinguishable, because they refer to the same entry in the process file table.
Charles Salvia
By safe i mean seek of fd1 will not interfere with seek of fd2, do u mean the same?
Drakosha
Yes .......................
Charles Salvia
+1  A: 

I think pwrite is an atomic operation if the number of bytes you're writing is less than PIPE_BUF of the pipe you're writing to (from the POSIX programmer's manual).

jilles de wit
Thanks, but let's assume it is atomic, then do we have a problem?
Drakosha
If it is atomic then I think by definition you do not have a problem. Atomic means the pwrite operation will be performed in one go without being interrupted by other threads.
jilles de wit