Is a successful call to write(2) atomic?

John Levine johnl at
Wed Jun 16 01:26:09 UTC 2021

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);


More information about the freebsd-questions mailing list