Last active
July 27, 2018 04:17
-
-
Save sighingnow/bfc640416347ae8b22db98678052675f to your computer and use it in GitHub Desktop.
Limit memory usage with libcgroup interface.
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
#include <assert.h> | |
#include <libcgroup.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#define _GNU_SOURCE | |
#include <unistd.h> | |
#define debug(fmt, ...) fprintf(stderr, "DEBUG: " fmt "\n", ##__VA_ARGS__) | |
int main() { | |
int ret = 0; | |
struct cgroup *g; | |
struct cgroup_controller *ctrl; | |
uint64_t mem_limit; | |
char *argv = {NULL}; | |
if ((ret = cgroup_init()) != 0) { | |
debug("failed to initialize cgroup environment."); | |
exit(0); | |
} | |
g = cgroup_new_cgroup("cglearn"); | |
ctrl = cgroup_add_controller(g, "memory"); | |
assert(ctrl != NULL); | |
assert(cgroup_set_value_uint64(ctrl, "memory.limit_in_bytes", 10000000) == 0); | |
assert(cgroup_create_cgroup(g, 0) == 0); | |
assert(cgroup_get_value_uint64(ctrl, "memory.limit_in_bytes", &mem_limit) == 0); | |
debug("mem_limit: %ld", mem_limit); | |
assert(cgroup_attach_task(g) == 0); | |
execvp("./allocate-fifty-mb.out", argv); | |
return 0; | |
} |
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
int main() { | |
int i; | |
void *p; | |
printf("starting...\n"); | |
for (i = 0; i < 50; ++i) { | |
if ((p = malloc(1<<20)) == NULL) { | |
printf("memory alloc failed at %d MB\n", i); | |
exit(0); | |
} | |
sleep(1); | |
memset(p, 0x00, 1<<20); | |
printf("allocate %d to %d MB at %p\n", i, i+1, p); | |
} | |
printf("done"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello,sighingnow. I am interested to know that How do you integrate libcgroup into your code?