Is write(2) "atomic" ?

bzs at bu-cs.UUCP bzs at bu-cs.UUCP
Wed Jul 13 03:08:00 AEST 1988


>Do UNIX semantics guarantee that write(2) calls will be "atomic" ?
>
>Suppose, process A executes write(fd, "123", 3) and process B
>executes write(fd, "456", 3) "concurrently". The file descriptor fd
>is shared between them (the file was creat(2)'ed for writing by the
>common parent of A and B). Does UNIX guarantee that the contents of
>the descriptor will be "123456" or "456123" (depending on which of
>A and B won the race) but never "124536" ? Does it make a difference
>whether the descriptor is a pipe or a terminal or a disk file or a
>tape drive or something else ?
>
>		      Naim Abdullah

There's another possibility which is hard to illustrate but more like
write(fd,"123456",6) and write(fd,"ABC",3) -> "123ABC456" (what I'm
trying to say is atomic in units of some page size or block boundary)
and yet another (infra vide.)

I think the result is indeterminate (undefined), a few experiments
here on various systems came up with some even stranger results than
the above (as if the file was just overwritten, more like "123ABC" for
the [expected] 9-char example above.)

Note to experimenters: try it with one buffer (single write) very
large, like 100K or more. With smallish buffers things tend to
serialize.

Anyhow, that's what file/record locking is all about (NFS seemed to
strictly serialize things, however, I'm not sure if that's guaranteed
at all but I can see how it is more likely, just luck probably?)

	-Barry Shein, Boston University



More information about the Comp.unix.wizards mailing list