http://linux.die.net/man/2/writev
The data transfers performed by readv() and writev() are atomic: the data written bywritev() is written as a single block that is notintermingled with output from writes in other processes (but seepipe(7) for an exception); analogously,readv() is guaranteed to read acontiguous block of data from the file, regardless of read operations performed in other threads or processes that have file descriptors referring to the sameopen file description (seeopen(2)).
//atomic_write.c
#include<stdio.h>
#include<unistd.h>
#include<sys/uio.h>
#include<string.h>
int main()
{
char* pbuf="&&&&&&&&&&&&&&&&&&&&&&&&\n";
char* cbuf="**********\n";
struct iovec iov_p;
struct iovec iov_c;
int pid;
iov_p.iov_base=pbuf;
iov_p.iov_len=strlen(pbuf);
iov_c.iov_base=cbuf;
iov_c.iov_len=strlen(cbuf);
pid=fork();
if(pid>0) while(1) writev(STDOUT_FILENO,&iov_p,1);
else if(pid==0) while(1) writev(STDOUT_FILENO,&iov_c,1);
else return -1;
}
POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic:the output data is written to the pipe as a contiguous sequence. Writes of more than PIPE_BUF bytes may be nonatomic: the kernel may interleave the datawith data written by other processes. POSIX.1-2001 requires PIPE_BUF to be at least 512 bytes. (On Linux, PIPE_BUF is 4096 bytes.) The precisesemantics depend on whether the file descriptor is nonblocking (O_NONBLOCK), whether there are multiple writers to the pipe, and on n, the numberof bytes to be written:
-
O_NONBLOCK disabled,
n <=
PIPE_BUF
- All n bytes are written atomically; write(2) may block if there is not room for n bytes to be written immediately O_NONBLOCK enabled, n <= PIPE_BUF
- If there is room to write n bytes to the pipe, then write(2) succeeds immediately, writing all n bytes; otherwise write(2) fails, with errno set to EAGAIN. O_NONBLOCK disabled, n > PIPE_BUF
- The write is nonatomic: the data given to write(2) may be interleaved with write(2)s by other process; the write(2) blocks until n bytes have been written. O_NONBLOCK enabled, n > PIPE_BUF
- If the pipe is full, then write(2) fails, with errno set to EAGAIN. Otherwise, from 1 to n bytes may be written (i.e., a"partial write" may occur; the caller should check the return value from write(2) to see how many bytes were actually written), and these bytesmay be interleaved with writes by other processes.