Is a successful call to write(2) atomic?

Ronald F. Guilmette rfg at tristatelogic.com
Tue Jun 15 21:40:39 UTC 2021


In message <CADqw_gKYTV-tRKxPFD1q78_gnpR2DWwmkTxLZJFmo4CUGqGqsg at mail.gmail.com>
Michael Schuster <michaelsprivate at gmail.com> wrote:

>Let's take a step back: an atomic write() either writes everything or
>nothing - and that's all.

Well, it *could* just do a partial write, and then return a short write
count, but my code checks for that and causes the process to die a
horrible and abundantly noisy death if it ever happens.  (In practice
and over many many runs, it has not happened even once.)

Anyway, my reading of the man page is that the only cases where write() 
might return a short count is when the FD being written to is some
sort of a network socket, which is not relevant in this case (because
I am writing to a disk file).

>There's nothing in that claim that says
>"everything must be in a contiguous block", nor, that all the data must be
>written in a single "operation" by the underlying system.

Indeed, and arguably the kernel *must* break up a buffer full of data
that was passed in a single call to write() into multple parts in some
instances, e.g. when writing to either an SSD or a good old "spinning
rust" hard drive would cross a physical block boundary.

My hope, of course, is that the entire buffer passed to write() would still
end up being written contiguously on the physical medium.

>So after consideration I don't think the observed behaviour is violating
>the claim that write() is atomic - I welcome correction, of course :-)

I frankly don't know.  It seems highly likely to me that Posix is most
probably very precise in defining the behavior, but one would have to
wade through a hundred pages or so to find the exact and crisp answer.


Regards,
rfg


More information about the freebsd-questions mailing list