Last active
November 19, 2015 18:31
-
-
Save timtadh/3d6ab5681a85ab00801c to your computer and use it in GitHub Desktop.
mmap-test
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
*swp | |
*swo | |
*.o | |
mmtest |
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
%.o:%.c | |
gcc -c -g -m32 -o $@ $< | |
mmtest: mmtest.o | |
gcc -g -m32 -o $@ $^ | |
mmtest.o: mmtest.c | |
.PHONY: clean | |
clean: | |
-@rm *.o main &> /dev/null | |
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 <errno.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
int pmap() { | |
char buf[4096]; | |
snprintf(buf, 4096, "vmmap %d", getpid()); // darwin version | |
// snprintf(buf, 4096, "pmap %d", getpid()); // linux version | |
system(buf); | |
} | |
int main(int argc, char **argv) { | |
size_t LEN = 4096; | |
void *addr = NULL; | |
void *addr2 = NULL; | |
int err = 0; | |
int *arr = NULL; | |
int i = 0; | |
addr = mmap( NULL, LEN, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); | |
fprintf(stderr, "mmap addr %p\n", addr); | |
if (addr == MAP_FAILED) { | |
int err = errno; | |
char *msg = NULL; | |
errno = 0; | |
msg = strerror(err); | |
fprintf(stderr, "mmap error %s\n", msg); | |
return -1; | |
} | |
arr = (int *)addr; | |
for (i = 0; i < LEN/4; i++) { | |
arr[i] = i; | |
} | |
fprintf(stderr, "expected mmap addr2 %p\n", addr + LEN); | |
addr2 = mmap(addr + LEN, LEN, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED, -1, 0); | |
if (addr2 == MAP_FAILED) { | |
int err = errno; | |
char *msg = NULL; | |
errno = 0; | |
msg = strerror(err); | |
fprintf(stderr, "mmap error %s\n", msg); | |
return -1; | |
} | |
fprintf(stderr, "mmap addr2 %p\n", addr2); | |
pmap(); | |
for (i = LEN/4; i < (LEN*2)/4; i++) { | |
arr[i] = 0xff; | |
} | |
for (i = 0; i < (LEN*2)/4; i++) { | |
fprintf(stdout, "arr %d %d\n", i, arr[i]); | |
} | |
err = munmap(addr, LEN * 2); | |
if (err != 0) { | |
int err = errno; | |
char *msg = NULL; | |
errno = 0; | |
msg = strerror(err); | |
fprintf(stderr, "munmap error %s\n", msg); | |
return -1; | |
} | |
pmap(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment