linux c 定位读取数据pread

来源:互联网 发布:淘宝客服心得体会 编辑:程序博客网 时间:2024/05/18 09:26

今天看代码发现有个 pread,发现这个好用啊。

是一个原子操作,集成了 lseek和read,不会被中断。  


NAME       pread, read - read from a fileSYNOPSIS       #include <unistd.h>       ssize_t pread(int fd, void *buf, size_t nbyte, off_t offset);       ssize_t read(int fd, void *buf, size_t nbyte);


代码如下:

#include<stdio.h>#include<stdlib.h>#include<fcntl.h>int a=6666;main(){char filename[100];int fd;int data;sprintf(filename,"/proc/%d/mem",getpid());//本程序虚拟内存文件fd=open(filename,O_RDWR);if(fd==-1) printf("open error:%m\n"),exit(-1);pread(fd,&data,4,(off_t)&a);    //从虚拟内存的相同地址中,读取实际地址位置相同的数据到data中//pread() = lseek()+read()//lseek(fd,(off_t)&a,SEEK_SET);//read(fd,&data,4);   printf("%d\n",data);close(fd);}


原创粉丝点击