一、函数声明
#include <unistd.h>
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
二、解释
pread其实是lseek和read的组合成的原子操作。(通过一次系统调用完成,lseek和read)
write同理。lseek和write
三、实例
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char **args)
{
int fd = open("test1", O_RDWR|O_CREAT, S_IRWXU);
char *p_buf = 0;
int str_len = -1;
if (argc < 2) {
printf("please input args\n");
exit(-1);
}
str_len = strlen(*(args + 1));
p_buf = (char *)malloc(str_len + 1);
pwrite(fd, *(args + 1), str_len, 0);
pread(fd, p_buf, str_len + 1, 0);
printf("%s\n", p_buf);
free(p_buf);
return 0;
}
// 运行结果
hotice0@ubuntu:~/Documents/Unix_Program$ ./file-io/pwrite_write hotice0
hotice0
实际上就是将bash传给程序的第二个参数,写入到文件并从文件读取。
四、意义
可以看到写入或者读取,只需要进行一次系统调用。相比lseek、write,lseek、read实现这个程序。少了一半的系统调用。减少系统调用就,可以用于特殊场景的性能优化。

Linux中的pwrite和pread函数是lseek和read/write的组合,提供原子操作,通过一次性系统调用来实现文件的读写。这种设计减少了系统调用的次数,对于特定场景的性能提升有显著作用。文章通过实例解析了这两个函数的使用,并探讨了其意义。
1450

被折叠的 条评论
为什么被折叠?



