Is the write(2) system call atomic

Kevin D. Clark kclark at mtghouse.com
Fri Apr 7 18:01:46 EDT 2006


Jerry Feldman writes:

> Here is a short code fragment to illustrate where the parent process creates 
> and opens a file for writing, then forks a child. it was my impression that 
> the kernel maintains a single structure for each open file. If that is true 
> then we would see all 6 lines. In most of the failure cases we see that the 
> first line and part of the second line of the parent are overwritten by the 
> child. 

Thoughts:

1:  what kind of thing are your writing to?  A file on a POSIX
compliant filesystem?  A file on a non-POSIX-compliant filesystem?  A
named pipe?  Etc.  All of these things have different semantics.

2:  It is true that the file table is shared between parent and child
here.  But you don't have any synchronization.

3a:  write() is not atomic.  Parent and child can access the shared
file table at the same time and update data here.

3b:  If you really want an atomic write(), try pwrite().

4:  The results that you see are legal, because the write() that you
are using is non-atomic and you aren't doing any other form of
synchronization.

Hope this helps,

--kevin
-- 
GnuPG ID: B280F24E                     And the madness of the crowd
alumni.unh.edu!kdc                     Is an epileptic fit
                                       -- Tom Waits




More information about the Discuss mailing list