Advertisement
Guest User

Juliano

a guest
Sep 24th, 2010
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. /*
  2.  * Demonstrate madvice() usage on Linux.
  3.  * See: http://stackoverflow.com/questions/3788977/linux-memory-mapped-files-reserve-lots-of-physical-memory
  4.  *
  5.  * Usage: madvtest FILENAME y/n
  6.  * Use a very big file as first argument, and pass 'y' as second argument
  7.  * to enable the call madvice(..., MADV_SEQUENTIAL);
  8.  */
  9.  
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <assert.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. #include <fcntl.h>
  16. #include <sys/mman.h>
  17. #include <sys/types.h>
  18. #include <sys/stat.h>
  19. #include <sys/resource.h>
  20.  
  21. #define CHUNK 1048576
  22. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  23.  
  24. int main(int argc, char **argv) {
  25.     int fd, i;
  26.     char *data, *end, *p, buf[CHUNK];
  27.     struct stat stbuf;
  28.     struct rusage usage;
  29.  
  30.     assert(argc == 3);
  31.     assert((fd = open(argv[1], O_RDONLY)) > 0);
  32.     assert(fstat(fd, &stbuf) == 0);
  33.     assert((data = mmap(NULL, stbuf.st_size, PROT_READ, MAP_SHARED, fd, 0)) != MAP_FAILED);
  34.     end = data + stbuf.st_size;
  35.    
  36.     if (argv[2][0] == 'y')
  37.         assert(madvise(data, stbuf.st_size, MADV_SEQUENTIAL) == 0);
  38.  
  39.     for (i = 0, p = data; p < end; p += CHUNK, i++) {
  40.         memcpy(buf, p, MIN(CHUNK, end - p));    // read 1 MB from mmapped file
  41.         if (i % 200 == 0) {
  42.             assert(getrusage(RUSAGE_SELF, &usage) == 0);
  43.             printf("%6d : %5ld MB\n", i, usage.ru_maxrss / 1024);
  44.             fflush(stdout);
  45.         }
  46.     }
  47.  
  48.     munmap(data, stbuf.st_size);
  49.     close(fd);
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement