Skip to content

Instantly share code, notes, and snippets.

@artob
Created November 19, 2009 18:06
Show Gist options
  • Save artob/238939 to your computer and use it in GitHub Desktop.
Save artob/238939 to your computer and use it in GitHub Desktop.
lockmem.c: grabs and locks a specified amount of memory
/**
* lockmem.c: grabs and locks a specified amount of memory
*
* Written by Arto Bendiken <http://ar.to/>
* Compile using "gcc -o lockmem lockmem.c"
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
void lockmem_abort(char* err) {
perror(err);
exit(1);
}
void* lockmem_alloc(size_t bytes) {
void* memory = malloc(bytes);
if (memory == NULL) {
lockmem_abort("malloc");
}
return memory;
}
void lockmem_lock(void* memory, size_t bytes) {
if (mlock(memory, bytes)) {
lockmem_abort("mlock");
}
}
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: lockmem BYTES\n");
exit(-1);
}
else {
size_t bytes = atoi(argv[1]);
if (strchr(argv[1], 'k') || strchr(argv[1], 'K')) {
bytes *= 1024;
}
if (strchr(argv[1], 'm') || strchr(argv[1], 'M')) {
bytes *= 1024 * 1024;
}
if (strchr(argv[1], 'g') || strchr(argv[1], 'G')) {
bytes *= 1024 * 1024 * 1024;
}
printf("Grabbing & locking %zd bytes of memory...", bytes);
void* memory = lockmem_alloc(bytes);
lockmem_lock(memory, bytes);
printf("done.\nPress any key to release memory and terminate...");
getchar(); // wait for keypress
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment