[linux]原子化的写文件操作writev

213 篇文章 0 订阅
writev()和readv()的数据传输是原子性的,保证了数据的完整性和不被其他进程的写操作干扰。对于小于PIPE_BUF字节的write(2)操作,POSIX.1-2001规定必须是原子性的,而大于此值的写操作可能非原子,可能会与其他进程的数据交错。在Linux上,PIPE_BUF为4096字节,具体语义取决于文件描述符是否为非阻塞、是否有多个管道写入者以及要写入的字节数n。
摘要由CSDN通过智能技术生成

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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值