1 #include <assert.h> 2 #include <stdlib.h> 3 #include <sys/mman.h> 4 #include <unistd.h> 5 6 static void test_anonymous(void) 7 { 8 int pagesize = getpagesize(); 9 char *page; 10 int ret; 11 12 page = mmap(NULL, pagesize, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); 13 assert(page != MAP_FAILED); 14 15 /* Check that mprotect() does not interfere with MADV_DONTNEED. */ 16 ret = mprotect(page, pagesize, PROT_READ | PROT_WRITE); 17 assert(ret == 0); 18 19 /* Check that MADV_DONTNEED clears the page. */ 20 *page = 42; 21 ret = madvise(page, pagesize, MADV_DONTNEED); 22 assert(ret == 0); 23 assert(*page == 0); 24 25 ret = munmap(page, pagesize); 26 assert(ret == 0); 27 } 28 29 static void test_file(void) 30 { 31 char tempname[] = "/tmp/.cmadviseXXXXXX"; 32 int pagesize = getpagesize(); 33 ssize_t written; 34 char c = 42; 35 char *page; 36 int ret; 37 int fd; 38 39 fd = mkstemp(tempname); 40 assert(fd != -1); 41 ret = unlink(tempname); 42 assert(ret == 0); 43 written = write(fd, &c, sizeof(c)); 44 assert(written == sizeof(c)); 45 page = mmap(NULL, pagesize, PROT_READ, MAP_PRIVATE, fd, 0); 46 assert(page != MAP_FAILED); 47 48 /* Check that mprotect() does not interfere with MADV_DONTNEED. */ 49 ret = mprotect(page, pagesize, PROT_READ | PROT_WRITE); 50 assert(ret == 0); 51 52 /* Check that MADV_DONTNEED resets the page. */ 53 *page = 0; 54 ret = madvise(page, pagesize, MADV_DONTNEED); 55 assert(ret == 0); 56 assert(*page == c); 57 58 ret = munmap(page, pagesize); 59 assert(ret == 0); 60 ret = close(fd); 61 assert(ret == 0); 62 } 63 64 int main(void) 65 { 66 test_anonymous(); 67 test_file(); 68 69 return EXIT_SUCCESS; 70 } 71