1 緣由
在閱讀seastar
源碼時(shí)發(fā)現(xiàn)有使用pread
函數(shù),這也是第一次認(rèn)識(shí)pread
函數(shù)雪位,平時(shí)用read
比較多竭钝。
2 pread函數(shù)
函數(shù)原型:
#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
簡(jiǎn)單來說就是在指定偏移offset
位置開始讀取count
個(gè)字節(jié),同理可推``pwrite`雹洗。
2.1 使用示例
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int fd = open("test.txt", O_RDONLY);
if(fd < 0)
{
perror("open failed");
return 1;
}
char buf[1024] = {0};
int offset = 5;
ssize_t ret = 0;
int count = 10;
if((ret = pread(fd, buf, count, offset)) == -1)
{
perror("pread failed");
return 1;
}
std::cout << "read buf = " << buf << std::endl;
return 0;
}
2.3 與read和write區(qū)別
man手冊(cè)是這樣說的:
The
pread()
andpwrite()
system calls are especially useful in multi‐
threaded applications. They allow multiple threads to perform I/O on
the same file descriptor without being affected by changes to the file
offset by other threads.
就是對(duì)于對(duì)多線程讀寫比較有意義香罐,不會(huì)相互影響讀寫文件時(shí)的offset
,這也是多線程時(shí)讀寫文件一個(gè)頭痛的問題时肿。不過我仔細(xì)一想庇茫。
- 對(duì)于
pwrite
來說,多個(gè)線程之間即使不影響offset
但還是存在使用上的問題螃成。 - 對(duì)于
pread
來說是可以解決多個(gè)線程offset
相互影響的問題旦签。
參考鏈接 文件IO詳解(十三)---pread函數(shù)和pwrite函數(shù)詳解里提到pread函數(shù)相當(dāng)于先后調(diào)用了lseek和read函數(shù),但是還是有區(qū)別的寸宏,有以下兩點(diǎn)區(qū)別:1. pread函數(shù)是原子操作宁炫,而先后調(diào)用兩個(gè)函數(shù)不是原子操作;2. pread函數(shù)是不會(huì)改變當(dāng)前文件偏移量的,而read和write函數(shù)會(huì)改變當(dāng)前文件偏移量
氮凝。第二點(diǎn)是關(guān)鍵羔巢,第一點(diǎn)暫時(shí)沒有核實(shí)是否正確。