Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Demonstrate madvice() usage on Linux.
- * See: http://stackoverflow.com/questions/3788977/linux-memory-mapped-files-reserve-lots-of-physical-memory
- *
- * Usage: madvtest FILENAME y/n
- * Use a very big file as first argument, and pass 'y' as second argument
- * to enable the call madvice(..., MADV_SEQUENTIAL);
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/resource.h>
- #define CHUNK 1048576
- #define MIN(a, b) ((a) < (b) ? (a) : (b))
- int main(int argc, char **argv) {
- int fd, i;
- char *data, *end, *p, buf[CHUNK];
- struct stat stbuf;
- struct rusage usage;
- assert(argc == 3);
- assert((fd = open(argv[1], O_RDONLY)) > 0);
- assert(fstat(fd, &stbuf) == 0);
- assert((data = mmap(NULL, stbuf.st_size, PROT_READ, MAP_SHARED, fd, 0)) != MAP_FAILED);
- end = data + stbuf.st_size;
- if (argv[2][0] == 'y')
- assert(madvise(data, stbuf.st_size, MADV_SEQUENTIAL) == 0);
- for (i = 0, p = data; p < end; p += CHUNK, i++) {
- memcpy(buf, p, MIN(CHUNK, end - p)); // read 1 MB from mmapped file
- if (i % 200 == 0) {
- assert(getrusage(RUSAGE_SELF, &usage) == 0);
- printf("%6d : %5ld MB\n", i, usage.ru_maxrss / 1024);
- fflush(stdout);
- }
- }
- munmap(data, stbuf.st_size);
- close(fd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement