mmap anonymous

This commit is contained in:
Ciro Santilli 六四事件 法轮功
2019-08-11 00:00:02 +00:00
parent c03d5d18ea
commit b1767533af
8 changed files with 92 additions and 23 deletions

24
userland/linux/brk.c Normal file
View File

@@ -0,0 +1,24 @@
/* https://cirosantilli.com/linux-kernel-module-cheat#brk */
#define _GNU_SOURCE
#include <assert.h>
#include <unistd.h>
int main(void) {
void *b = sbrk(0);
int *p = (int *)b;
/* Move it 2 ints forward */
brk(p + 2);
/* Use the ints. */
*p = 1;
*(p + 1) = 2;
assert(*p == 1);
assert(*(p + 1) == 2);
/* Deallocate back. */
brk(b);
return 0;
}

View File

@@ -0,0 +1,40 @@
/* https://cirosantilli.com/linux-kernel-module-cheat#mmap-map-anonymous */
#define _GNU_SOURCE
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
int *is;
size_t nbytes = 2 * sizeof(*is);
/* Allocate 2 ints. */
is = mmap(
NULL,
nbytes,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS,
-1,
0
);
/* This can happen for example if we ask for too much memory. */
if (is == NULL) {
perror("mmap");
exit(EXIT_FAILURE);
}
/* Write to and read from the allocated memory. */
is[0] = 1;
is[1] = 2;
assert(is[0] == 1);
assert(is[1] == 2);
/* Free the allocated memory. */
munmap(is, nbytes);
return EXIT_SUCCESS;
}