mmap
fopen
and fwrite
FILE*
offset
and a whence
originlseek
How do we implement this? Page faults!
Now, the pages can be tied to file pages, instead of pages backed by physical RAM.
mmap
is called, it’s possible that none of the file is loaded into memory yet.mmap
is complicated! Here is the signature:
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
Basic mapping parameters:
addr
: Page aligned address to start the mapping at or NULL
to let mmap
chooselength
: Byte length of mappingCommon access settings:
prot
: Memory protection (r/w/x/none)flags
: Update visibility to other processes (ex. MAP_SHARED
/ MAP_PRIVATE
) or define a non-file mapping (MAP_ANONYMOUS
)File mapping options:
fd
: File descriptor used in a file mappingoffset
: Page-aligined offset in a file to begin a mapping atSee the man page for more!
lookup1.c
)mmap
(lookup2.c
)Here’s a serialization using an inorder traversal:
Another example with a level-ordered traversal:
We will use file offsets:
4
in a correct file.0
is analogous to a NULL
ptr.typedef struct {
uint32_t left_child; // offset of node containing left child
uint32_t right_child; // offset of node containing right child
// Offsets are relative to the beginning of the file.
// An offset of zero means the child does not exist.
uint32_t count; // number of times the word occurs in the data set
float price; // price of the word
char word[0]; // contents of the word, null-terminated
} BinaryTreeNode;
Recall malloc
!
// allocate 12 bytes for word
BinaryTreeNode* node1 = malloc(sizeof(BinaryTreeNode) + 12);
// allocate 20 bytes for word
BinaryTreeNode* node2 = malloc(sizeof(BinaryTreeNode) + 20);
strcmp
on the word
field of each node to traverse the tree.create_data
for making your own BTRE fileslookup1-reference
/ lookup2-reference
for comparison