2015-11-07 94 views
1

在Linux上(Linux 3.16.0-38-generic#52〜14.04.1-Ubuntu x86_64 GNU/Linux),當試圖通過直接寫入文件io與O_DIRECT旗啓用,似乎寫後,該文件仍然是空的,請幫助。直接io - 當寫入文件時O_DIRECT似乎不工作

順便說一下,我知道直接io應該通常與程序級緩存一起使用,下面的程序只是想對直接io進行測試。

direct_io_test.c:

// direct io test 

#define _GNU_SOURCE 
#include <stdio.h> 
#include <errno.h> 
#include <string.h> 
#include <unistd.h> 
#include <fcntl.h> 

int direct_io_test() { 
    char *fp= "/tmp/direct_io.txt"; 
    int flag = O_RDWR | O_CREAT | O_APPEND | O_DIRECT; 
    mode_t mode = 0644; 

    int fd = open(fp, flag, mode); 
    if (fd == -1) { 
     printf("Failed to open file. Error: \t%s\n", strerror(errno)); 
     return errno; 
    } else { 
     printf("Succeed to open file, file descriptor: %d\n", fd); 
    } 

    // TODO ... seems didn't write to file, 
    write(fd, "hello\n", 6); 

    close(fd); 
    return 0; 
} 

int main(int argc, char *argv[]) { 
    direct_io_test(); 

    return 0; 
} 
+0

您發佈了錯誤代碼?沒有提及'O_DIRECT'。 – kaylum

+0

大概是在fcntl.h? –

+0

@MartinJames是的,它來自'fcntl.h'並且需要'#define _GNU_SOURCE'。 –

回答

1

檢查從寫返回值。您從中複製的字符串文字可能沒有正確對齊內存中的O_DIRECT,因此寫入調用可能會失敗。

+0

是的,'write()'失敗,出現'Invalid argument',可能是因爲沒有達到'O_DIRECT'所要求的內存對齊。它似乎不應該複製'O_DIRECT'的文字字符串。 –