Created
December 16, 2017 14:00
-
-
Save s3rvac/73cfd55d7348ced3cf0c9be243a2a27e to your computer and use it in GitHub Desktop.
Limiting the maximal virtual memory of a process within itself on Linux.
This file contains hidden or 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
// | |
// Limits the maximal virtual memory of the process to half of the total | |
// amount of RAM on the system. | |
// | |
// Linux only. | |
// | |
// Compilation: | |
// | |
// gcc -std=c11 -pedantic limit-virtual-memory.c -o limit-virtual-memory | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/resource.h> | |
#include <sys/sysinfo.h> | |
int main() { | |
// Find the total amount of RAM on the system. | |
struct sysinfo system_info; | |
int rc = sysinfo(&system_info); | |
if (rc != 0) { | |
perror("error: sysinfo() failed"); | |
exit(1); | |
} | |
size_t total_ram = system_info.totalram; | |
printf("Total RAM: %4lu GB\n", total_ram / 1024 / 1024 / 1024); | |
size_t limited_ram = total_ram / 2; | |
printf("Limiting to: %4lu GB\n", limited_ram / 1024 / 1024 / 1024); | |
// Limit the virtual memory for the process. | |
struct rlimit limit = { | |
.rlim_cur = limited_ram, // Soft limit. | |
.rlim_max = RLIM_INFINITY // Hard limit (ceiling for rlim_cur). | |
}; | |
rc = setrlimit(RLIMIT_AS, &limit); | |
if (rc != 0) { | |
perror("error: setrlimit() failed"); | |
exit(1); | |
} | |
// Verification. | |
// This should succeed: | |
void* mem1 = malloc(limited_ram / 2); | |
if (mem1 == NULL) { | |
fprintf(stderr, "error: unexpectedly failed to allocate memory\n"); | |
exit(1); | |
} | |
free(mem1); | |
// This should fail: | |
void* mem2 = malloc(limited_ram); | |
if (mem2 != NULL) { | |
free(mem2); | |
fprintf(stderr, "error: unexpectedly succeeded to allocate memory\n"); | |
exit(1); | |
} | |
free(mem2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment