Is a successful call to write(2) atomic?
steve at sohara.org
Wed Jun 16 08:12:04 UTC 2021
On Wed, 16 Jun 2021 00:39:27 -0700
"Ronald F. Guilmette" <rfg at tristatelogic.com> wrote:
> In message <20210616072633.e4bd29839249465e385bbf6f at sohara.org>,
> Steve O'Hara-Smith <steve at sohara.org> wrote:
> > IOW if one process writes ABC and another writes DEF both at the
> >end of file you might get ABCDEF but you won't get ABDCEF you might also
> >get ABDEF as D overwrites C...
> Yup. Some of the "garbled" lines I have been getting look suspiciously
> like the "ABDEF" in your example.
> > John's code will work (it is the standard solution) - provided
> >*every* writer uses it - without the O_APPEND you would need to put a
> >seek to EOF inside the locked section which is the pattern I most often
> >wind up with.
> So the O_APPEND by itself isn't enough to fix the problem? I still have
> to wrap the calls to write() inside some sort of locking code?
Correct, the O_APPEND just ensures that the write will start at the
EOF at the time the write is called.
> I'll try both... O_APPEND, with and without locking... but it kind of
> seems to me that if O_APPEND, by itself, were actually doing what the man
> page says it does, then that alone ought to be enough to prevent garbling
> of the output lines.
No, in the ABDEF example the ABC process calls write and finds the
end of file and sets up ABC to be written there then the DEF process calls
write and finds EOF when the A and B have been written out but not C however
C gets written between the DEF process finding the end of file and writing
D out so C gets written and then overwritten. The O_APPEND guarantee that
the blocks are written contiguously starting at EOF is held but nothing
prevents the blocks from two writers interleaving and writing over each
Steve O'Hara-Smith <steve at sohara.org>
More information about the freebsd-questions