Re: PROBLEM: pthread-safety bug in write(2) on Linux 2.6.x

From: Linus Torvalds
Date: Thu Apr 27 2006 - 11:24:00 EST




On Thu, 27 Apr 2006, Samuel Thibault wrote:
>
> I'm getting a bit late in the discussion, but this is a bug that we've
> here known for quite some time now. The easy fix for getting correct
> concurrent writes was to add a pipe: instead of calling
>
> my_parallel_program > log
>
> just call
>
> my_parallel_program | tee log
>
> the pipe guarantees atomicity.

Side note: the pipe only guarantees atomicity for writes smaller than
PIPE_BUF (normally 4kB on linux).

For larger writes, you'll still see all the data exactly once, but
individual write() calls may have their contents mixed up. Ie if two
processes or threads each do a 8kB write, the reader might see 4kB from
the first thread, 4kB from the second, and then the remaining 4kB from the
first again (or any other pattern - you could see alternating bytes,
although in practice that is obviously not what is going to happen).

And yes, that atomicity is actually guaranteed by standards, so this is
portable, and how you should do things if you care.

Linus
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/