原子操作——pread()和pwrite()
Posted ys6738-4271-3931
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原子操作——pread()和pwrite()相关的知识,希望对你有一定的参考价值。
1、pread()、pwrite()函数与read()、write()函数的区别在于是否更新当前文件偏移量;
2、pread:相当于调用lseek后再调用read函数;
调用pread时,无法中断其定位和读操作,且不更新当前文件偏移量。pwrite()函数与此相同。
3、函数原型:
ssize_t pread(int fd,void *buf,size_t nbytes,off_t offset);
ssize_t pwrite(int fd,void *buf,size_t nbytes,off_t offset);
4、头文件:#include <unistd.h>
5、示例:
1 #include <stdio.h> 2 #include <fcntl.h> 3 #include <unistd.h> 4 #include <sys/types.h> 5 #include <string.h> 6 7 int main(int argc,char *argv[]) 8 { 9 int fd = open("pread.txt",O_RDWR|O_CREAT,0777); 10 int num = write(fd,"Hello World! ",strlen("Hello World! ")); 11 if (num < 0) 12 { 13 perror("write error! "); 14 return -1; 15 } 16 int offset = lseek(fd,0,SEEK_CUR); 17 printf("num = %d,offset = %d ",num,offset); // num = 13,offset = 13; 18 19 pwrite(fd,"My Best Friends!",strlen("My Best Friends!"),6); 20 21 char buf[20] = "",buf1[20] = ""; 22 int ret = read(fd,buf,sizeof(buf)); 23 if (ret < 0) 24 { 25 perror("read error! "); 26 return -1; 27 } 28 29 int offset1 = lseek(fd,0,SEEK_CUR); 30 printf("ret = %d,offset1 = %d ",ret,offset1); // ret = 9,offset1 = 22; 31 32 pread(fd,buf1,sizeof(buf1),6); 33 printf("buf = %s,buf1 = %s ",buf,buf1);// buf = Friends!,buf1 = My Best Friends! 34 35 return 0; 36 }
以上是关于原子操作——pread()和pwrite()的主要内容,如果未能解决你的问题,请参考以下文章
我该怎么做才能找到 pread64/pwrite64 挂起的原因?
Linux系统函数read()/write()/pread()/pwrite()的区别-(转自CSDN网络)