O_APPEND的原子性操作

/**
* @function: atomic_append.c 
*
* @brief: in this function we will show how to use O_APPEND flag to guarantee atomic operation.
*         first function will open filename(if necessary creat it), and use write() add a byte
*         at the end of file(use O_APPEND), all is num-bytes. if have x parm, use lseek.
*
* @parm: $atomic_append filename num-bytes [x]
*
* @log: yulong -2017/08/03 first edit
**/
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
    int InputFd=0;
    mode_t filePerms;
    int num_bytes, count, num_write;
    
    filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
    			S_IROTH | S_IWOTH; /* RW-RW-RW--*/
    if((argc != 3) && (argc != 4))
        printf("please enter correct parm.\n");
    
    num_bytes=atoi(argv[2]); //save num_bytes
    if(argc == 3) //use append flag
    {
    	printf("argc == 3\n");
        if((InputFd=open(argv[1], O_RDWR|O_CREAT|O_APPEND, filePerms)) == -1) //double bracket!! 
        	perror("open error.\n"); 
        for(count=0; count<num_bytes; count++)
        {
        	num_write = write(InputFd, "1", 1);	 //write one bit at a time
        }
        if(close(InputFd) == -1)
        	perror("close error.\n");
    }
    else if(argc == 4 && strcmp(argv[3], "x")==0) //use lseek
    {
    	printf("argc == 4\n");
    	if((InputFd=open(argv[1], O_RDWR|O_CREAT, filePerms)) == -1)  
        	perror("open error.\n"); 
        for(count=0; count<num_bytes; count++)
        {
        	if(lseek(InputFd, 0, SEEK_END) == -1)
  	    		perror("lseek error\n");
        	num_write = write(InputFd, "1", 1);	 //write one bit at a time
        }
        if(close(InputFd) == -1)
        	perror("close error.\n");
    }
}
编译后运行如下代码:


实验结果:
通过比较f1和f2文件大小的不同,说明了O_APPEND为原子操作,能很好的避免竞争关系。而采用sleek是不安全的操作方式。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值