Is a successful call to write(2) atomic?

Ronald F. Guilmette rfg at
Wed Jun 16 06:03:38 UTC 2021

In message <20210616012606.3C77A1183464 at ary.qy>, 
"John Levine" <johnl at> wrote:

>It appears that Ronald F. Guilmette <rfg at> said:
>>More to the point, if indeed each call to write() *is* "atomic"... at least
>>in the sense that the given buffer will be treated like an indivisable whole,
>>all of the way along its journey to some physical device... then why are
>>users nontheless being encouraged, still, to "use some form of concurrency
>>control"?  I mean what would be the point of that if in fact write() never
>>busts up the hunks of data given to it into separate sub-hunks?
>I think it depends on the device.  If I just want to write stuff to a log
>file and not get it scrambled, this should do the trick:
>  fd = open("somefile", O_CREAT|O_WRONLY|O_APPEND);
>  /* put some stuff in buf[] */
>  flock(fd, LOCK_EX);
>  write(fd, buf, strlen(buf)): /* O_APPEND ensures it's added at the end */
>  flock(fd, LOCK_UN);

Thanks John, but as I noted earlier in this thread, if the data passed to
write() in a single call isn't treated as an indivisible whole OR if each
of the (mutltiple) processes that are making the calls (using code as
you have written above) is maintaining its own separate file pointer,
then it isn't 100% clear that what you suggested will actually solve
the "garbling" problem.

I'm going to try passing all lines up to a parent process which will then
be the only one writing to the file, and see if that resolves the issue.


More information about the freebsd-questions mailing list