c - "O_DIRECT 512-byte aligned"是什么意思?

标签 c linux io

O_DIRECT mode introduces further requirements of all read and write operations to have their file offset, memory buffer and size be aligned to 512 bytes.

这到底是什么意思?

例如,

struct iocb cb;
char data[4096];
cb.aio_buf = (uint64_t)data;
cb.aio_offset = 512;
cb.aio_nbytes = 4096;

这是否意味着数据大小应该是 512*n ?偏移量应该是 512 * n?

我将 4096 更改为 7777,并将偏移量更改为 333,看起来工作正常。

最佳答案

Offset, buffer address, size必须对齐512字节,否则会报错 参数无效 (errno=-22)

下面是测试用例

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdint.h>
#include <errno.h>
#include <linux/aio_abi.h>
#include <syscall.h>

#define align(p, a) (((long)(p) + (a - 1)) & ~(a - 1))

static inline int io_setup(unsigned nr_events, aio_context_t *ctx_idp)
{
    return syscall(__NR_io_setup, nr_events, ctx_idp);
}

static inline int io_destroy(aio_context_t ctx)
{
    return syscall(__NR_io_destroy, ctx);
}

static inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp)
{
    return syscall(__NR_io_submit, ctx, nr, iocbpp);
}

static inline int io_getevents(aio_context_t ctx, long min_nr, long nr,
                               struct io_event *events, struct timespec *timeout)
{
    return syscall(__NR_io_getevents, ctx, min_nr, nr, events, timeout);
}


int main(int argc, char *argv[])
{
    int fd, rc;
    char data[8192];

    aio_context_t ctx = 0;
    struct io_event events;
    struct iocb cb;
    struct iocb *cblist[] = {&cb};

    fd = open("a.txt", O_CREAT | O_RDWR | O_DIRECT, 0666);

    if (fd < 0)
        return -1;

    rc = io_setup(1, &ctx);
    memset(&cb, 0, sizeof(cb));
    cb.aio_buf = align(data, 512);
    cb.aio_offset = 512;
    cb.aio_nbytes = 4096;
    cb.aio_fildes = fd;
    cb.aio_lio_opcode = IOCB_CMD_PWRITE;

    rc = io_submit(ctx, 1, cblist);

    if (rc < 0) {
        printf("io_submit: error=%d\n", rc);
        goto error_exit;
    }

    rc = io_getevents(ctx, 1, 1, &events, NULL);

    if (rc != 1) {
        fprintf(stderr, "io_getevents failed: %s.\n", strerror(errno));
        goto error_exit;
    }

    if (events.res < 0)
        printf("write error: %s (%lld)\n", strerror(-events.res), events.res);
    else
        printf("write result: %lld\n", events.res);

    rc = io_destroy(ctx);

error_exit:
    close(fd);
    return 0;
}

关于c - "O_DIRECT 512-byte aligned"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55447218/

相关文章:

C - do/while 循环和 switch(int)。输入 char 值会导致 inf。环形

java - 读/写项目文件夹中的文件

java - 在java中使用UTF-8编码读取文件时出现问题

c - 返回值和垃圾值的关系

c++ - 使用按位运算符的 MAX 16 个字符字符串的 Strlen

c - 为什么使用2个指针指向atmega微 Controller 中的寄存器地址?

linux - Apache 2.4 中的 SSL 证书错误

c++ - Mesa + Linux : gl. h 不包含现代 OpenGL

Python subprocess.call 函数不重定向输出

python - 支持文件名、路径和缓冲区输入