//使用 O_DIRECT 跳过缓冲区高速缓存
//#define _GNU_SOURCE /*Obtion O_DIRECT definition from <fcntl.h>*/
#include <fcntl.h>
#include <malloc.h>
#include "tlpi_hdr.h"
int
main(int argc,char *argv[])
{
int fd;
ssize_t numRead;
size_t length,alignment;
off_t offset;
void *buf;
if (argc < 3 || strcmp(argv[1],"--help") == 0)
usageErr("%s file length [offset [alignment]]\n",argv[0]);
length = getLong(argv[2],GN_ANY_BASE,"length");
offset = (argc > 3) ? getLong(argv[3],GN_ANY_BASE,"offset") : 0;
alignment = (argc > 4) ? getLong(argv[4],GN_ANY_BASE,"alignment") : 4096;
fd = open(argv[0],O_RDONLY | O_DIRECT);
if (fd == -1)
errExit("open");
/*memalign() allocates a block of memory aligned on an address that
is a multiple of ites first argument.The following expression
ensures the 'buf' is aligned on a non-power-of-two multiole of
'alignment' .We do this to ensure that if, for example, we ask
使用 O_DIRECT 跳过缓冲区高速缓存
使用O_DIRECT避免缓冲区高速缓存的文件读取
最新推荐文章于 2022-10-19 17:00:00 发布
该程序演示了如何利用O_DIRECT标志打开文件,以绕过内核缓冲区高速缓存,直接从磁盘读取数据。通过调整内存对齐和长度参数,确保读取操作的正确性。程序会根据提供的文件名、长度、偏移量和对齐方式执行读取操作,并展示读取到的字节数。当参数不符合要求(如长度不是对齐值的倍数或偏移量不对齐)时,read系统调用将返回错误。

最低0.47元/天 解锁文章
639

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



