使用 O_DIRECT 跳过缓冲区高速缓存

该程序演示了如何利用O_DIRECT标志打开文件,以绕过内核缓冲区高速缓存,直接从磁盘读取数据。通过调整内存对齐和长度参数,确保读取操作的正确性。程序会根据提供的文件名、长度、偏移量和对齐方式执行读取操作,并展示读取到的字节数。当参数不符合要求(如长度不是对齐值的倍数或偏移量不对齐)时,read系统调用将返回错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//使用 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
     fo a 256-byte aligned buffer, the we don't accidentally get
     a buffer that is also aligned on a 512-byte boundary.

     the '(char *)' cast is needed to allow pointer arithmetic (which
     is not possible on the 'void *' returned by memalign()).*/

    buf = (char *) memalign(alignment * 2,length + alignment) + alignment;
    if (buf == NULL)
        errExit("memalign");

    if (lseek(fd,offset,SEEK_SET) == -1)
        errExit("lseek");

    numRead = read(fd,buf,length);
    if (numRead == -1)
        errExit("read");
    printf("Read %ld bytes\n",(long) numRead);

    exit(EXIT_SUCCESS);
}
/*
 程序使用示例:
[root@localhost linux-test]# gl++ test.c
[root@localhost linux-test]#
[root@localhost linux-test]# ./a.out /test/x 512    //Read 512 bytes at offset 0
Read 512 bytes
[root@localhost linux-test]# ./a.out /test/x 256    //Length is not a multiple of 512
ERROR [EINVAL Invalid argument] read
[root@localhost linux-test]# ./a.out /test/x 512 1  //offset is not a multiple of 512
ERROR [EINVAL Invalid argument] read
[root@localhost linux-test]# ./a.out /test/x 4096 8192 512
Read 4096 bytes
[root@localhost linux-test]# ./a.out /test/x 4096 512 256   //alignment is not a multiple of 512
ERROR [EINVAL Invalid argument] read
[root@localhost linux-test]#
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值