直接讀取檔案
說明:使用 O_DIRECT 旗標來繞過緩衝區,直接讀寫設備或檔案。使用memalign()函數分配一塊記憶體,該記憶體區塊與其第一個參數以倍數對齊。
此範例使用O_DIRECT旗標開啟與讀寫文件,這個程式最多接受四個參數,依次指定要讀取的文件、要從文件中讀取的位元數、程式在從文件讀取之前應該查詢的偏移量,以及傳遞給 read() 的資料緩衝區。最後兩個參數是非必要的選項,預設是 0 偏移量以及 4096 個位元組。
Listing 13-1
direct_read.c
1
/*************************************************************************\
2
* Copyright (C) Michael Kerrisk, 2022. *
3
* *
4
* This program is free software. You may use, modify, and redistribute it *
5
* under the terms of the GNU General Public License as published by the *
6
* Free Software Foundation, either version 3 or (at your option) any *
7
* later version. This program is distributed without any warranty. See *
8
* the file COPYING.gpl-v3 for details. *
9
\*************************************************************************/
10
11
/* Listing 13-1 */
12
13
/* direct_read.c
14
15
Demonstrate the use of O_DIRECT to perform I/O bypassing the buffer cache
16
("direct I/O").
17
18
Usage: direct_read file length [offset [alignment]]
19
20
This program is Linux-specific.
21
*/
22
#define _GNU_SOURCE /* Obtain O_DIRECT definition from <fcntl.h> */
23
#include <fcntl.h>
24
#include <malloc.h>
25
#include "tlpi_hdr.h"
26
27
int
28
main(int argc, char *argv[])
29
{
30
int fd;
31
ssize_t numRead;
32
size_t length, alignment;
33
off_t offset;
34
char *buf;
35
36
if (argc < 3 || strcmp(argv[1], "--help") == 0)
37
usageErr("%s file length [offset [alignment]]\n", argv[0]);
38
39
length = getLong(argv[2], GN_ANY_BASE, "length");
40
offset = (argc > 3) ? getLong(argv[3], GN_ANY_BASE, "offset") : 0;
41
alignment = (argc > 4) ? getLong(argv[4], GN_ANY_BASE, "alignment") : 4096;
42
43
fd = open(argv[1], O_RDONLY | O_DIRECT);
44
if (fd == -1)
45
errExit("open");
46
47
/* memalign() allocates a block of memory aligned on an address that
48
is a multiple of its first argument. By specifying this argument as
49
2 * 'alignment' and then adding 'alignment' to the returned pointer,
50
we ensure that 'buf' is aligned on a non-power-of-two multiple of
51
'alignment'. We do this to ensure that if, for example, we ask
52
for a 256-byte aligned buffer, we don't accidentally get
53
a buffer that is also aligned on a 512-byte boundary. */
54
55
buf = memalign(alignment * 2, length + alignment);
56
if (buf == NULL)
57
errExit("memalign");
58
59
buf += alignment;
60
61
if (lseek(fd, offset, SEEK_SET) == -1)
62
errExit("lseek");
63
64
numRead = read(fd, buf, length);
65
if (numRead == -1)
66
errExit("read");
67
printf("Read %ld bytes\n", (long) numRead);
68
69
exit(EXIT_SUCCESS);
70
}
Last modified 7mo ago