What is the difference between `O_DIRECT | O_SYNC` + write() and `O_DIRECT` + write() + fsync()

随声附和 提交于 2021-02-11 12:49:01

问题


I want to know the difference between

    char *text = (char *)malloc(4096);
    memset(text, 'a', 4096);

    int fd = open(filepath, O_RDWR | O_CREAT | O_DIRECT);

    for(int i=0; i<1000; i++) {
        write(fd, (void *)text, 4096);
        fsync(fd);
    }

    close (fd);

and

    char *text = (char *)malloc(4096);
    memset(text, 'a', 4096);

    int fd = open(filepath, O_RDWR | O_CREAT | O_DIRECT | O_SYNC); //<----Difference

    for(int i=0; i<1000; i++) {
        write(fd, (void *)text, 4096);
        // fsync(fd);  <--------------------------------------------------Difference
    }

    close (fd);

The performance of the code above is way slower than that below.


回答1:


On the one hand there shouldn't be any difference because a similar amount of work has to happen in both cases (write then disk flush assuming no chicanery). On the other hand, the first case has to do twice as many syscalls so (in theory) has more overhead (especially if time it takes to make the syscall is a significant part of total time it takes to do the operation). In all probability it likely depends on the disk/kernel/CPU/size of I/O etc. as to whether there is a difference between the two and which is faster. Maybe in the second case the kernel can send the write down with the FUA bit set which would mean the difference could depend on just what file/device you were opening (because that may control whether such an optimisation can be done)...

Using O_SYNC also makes errors appear on the return of the write() call but as noted in other comments you're not checking the return codes...



来源:https://stackoverflow.com/questions/65828666/what-is-the-difference-between-o-direct-o-sync-write-and-o-direct-wr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!