unix环境高级编程-3.11-原子操作

上一节,我们学习了多个进程打开同一个文件,和单个进程打开多个文件原理。

1.填写至一个文件

早期的unix系统将数据添加文件尾端如下代码

if(lseek(fd,0l,2)<0
    err_sys("lseek error");
if(write(fd,buf,100)!=0
    err_sys("write error");


对单个进程可正常工作,但是多个进程就不能了。

UNIX提供了一种方法是这种操作成为原子操作,该方法是在打开文件时设置O_APPEND标志。就是每次写文件的时候,豆浆该文件的偏移量移动到尾端。

2.pread和pwrite函数

ssize_t pread (int filedes, void *buffer, size_t size, off_t offset)
                                                          ‘unistd.h’ (Unix98): Section 13.2 [Input and Output Primitives], page 299.
ssize_t pread64 (int filedes, void *buffer, size_t size, off64_t offset)
                                                           ‘unistd.h’ (Unix98): Section 13.2 [Input and Output Primitives], page 299.


pread返回值:返回字节数,若已经到文件结尾则返回0,出错返回-1;

pwrite返回值:若成功返回字节数,出错返回-1;

 

调用pread,相当于顺序调用lseek和read,但是pread 又与这种顺序调用下列有重要区别。

  • 调用pread时候,无法终端其定位和读操作。
  • 不更新文件指针。

 

调用pwrite相当于顺序调用lseek和write,原理同上。

 

3.创建一个文件

在对open函数的O_CREAT和O_EXCL选项进行说明时候就是原子操作。

下面是截取gun c手册的。

int open (const char *filename, int flags[, mode t mode]) [Function]
The open function creates and returns a new file descriptor for the file named by
filename. Initially, the file position indicator for the file is at the beginning of the file.
The argument mode is used only when a file is created, but it doesn’t hurt to supply
the argument in any case.
The flags argument controls how the file is to be opened. This is a bit mask; you create
the value by the bitwise OR of the appropriate parameters (using the ‘|’ operator in
C). See Section 13.14 [File Status Flags], page 333, for the parameters available.
The normal return value from open is a non-negative integer file descriptor. In the
case of an error, a value of

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值