Paste P369

Pinned memory
ActivePublic

Authored by Sergey Sharybin (sergey) on Jun 27 2016, 2:00 PM.
Tags
None
Subscribers
None
1#include <stdlib.h>
2#include <stdio.h>
3
4#include <sys/mman.h>
5
6#define TEST_LOCK
7
8int main(int argc, char **argv) {
9const size_t N = (size_t)10 * 1024 * 1024 * 1024;
10char *mem = malloc(sizeof(char) * N);
11printf("Memory allocated\n");
12#ifdef TEST_LOCK
13printf("Pinning memory...");
14fflush(stdout);
15if (mlock(mem, sizeof(char) * N) == -1) {
16printf(" fail!\n");
17perror("mlock");
18fprintf(stderr, "Error pinning memory, aborting!\n");
19return EXIT_FAILURE;
20}
21printf(" ok.\n");
22#endif
23size_t i;
24printf("Filling in memory..");
25fflush(stdout);
26for (i = 0; i < N; ++i) {
27mem[i] = i % 255;
28}
29printf(" ok.\n");
30printf("Hit enter to continue.\n");
31getchar();
32#ifdef TEST_LOCK
33printf("Unpinning memory...");
34fflush(stdout);
35munlock(mem, sizeof(char) * N);
36printf(" ok.\n");
37#endif
38printf("Freeing memory...");
39fflush(stdout);
40free(mem);
41printf(" ok.");
42printf("All done, exit!\n");
43return EXIT_SUCCESS;
44}
Sergey Sharybin (sergey) changed the title of this paste from untitled to Pinned memory.
Sergey Sharybin (sergey) updated the paste's language from autodetect to c.
Sergey Sharybin (sergey) changed the edit policy from "All Users" to "Administrators".