-
-
Save telles-simbiose/da0c8fc66b57078e7ef7fab3a5482b82 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <sys/mman.h> | |
#define FILEPATH "/tmp/mmapped.bin" | |
#define FILESIZE (512 * 1024 * 1024) | |
#define NBUFFERS 1000000 | |
#define ITERATIONS 100 | |
int main(int argc, char *argv[]) | |
{ | |
int i; | |
int j; | |
int fd; | |
int result; | |
long addr[NBUFFERS]; | |
/* Open a file for writing. | |
* - Creating the file if it doesn't exist. | |
* - Truncating it to 0 size if it already exists. (not really needed) | |
* | |
* Note: "O_WRONLY" mode is not sufficient when mmaping. | |
*/ | |
fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600); | |
if (fd == -1) { | |
perror("Error opening file for writing"); | |
exit(EXIT_FAILURE); | |
} | |
/* Stretch the file size to the size of the (mmapped) array of ints | |
*/ | |
result = lseek(fd, FILESIZE-1, SEEK_SET); | |
if (result == -1) { | |
close(fd); | |
perror("Error calling lseek() to 'stretch' the file"); | |
exit(EXIT_FAILURE); | |
} | |
/* Something needs to be written at the end of the file to | |
* have the file actually have the new size. | |
* Just writing an empty string at the current file position will do. | |
* | |
* Note: | |
* - The current position in the file is at the end of the stretched | |
* file due to the call to lseek(). | |
* - An empty string is actually a single '\0' character, so a zero-byte | |
* will be written at the last byte of the file. | |
*/ | |
result = write(fd, "", 1); | |
if (result != 1) { | |
close(fd); | |
perror("Error writing last byte of the file"); | |
exit(EXIT_FAILURE); | |
} | |
for (j = 0; j < ITERATIONS; j++) { | |
for (i = 0; i < NBUFFERS; i++) { | |
/* Now the file is ready to be mmapped. | |
*/ | |
addr[i] = mmap(4096 * i, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); | |
if (addr[i] == MAP_FAILED) { | |
close(fd); | |
perror("Error mmapping the file"); | |
exit(EXIT_FAILURE); | |
} | |
} | |
for (i = 0; i < NBUFFERS; i++) { | |
/* Don't forget to free the mmapped memory | |
*/ | |
if (munmap(addr[i], 4096) == -1) { | |
perror("Error un-mmapping the file"); | |
/* Decide here whether to close(fd) and exit() or not. Depends... */ | |
} | |
} | |
} | |
/* Un-mmaping doesn't close the file, so we still need to do that. | |
*/ | |
close(fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment