Set process memory limit in C (with fork and exec)

I want to start a process with a memory limit set (ideally a data segment, stack and heap) My code looks something like

child = fork(); if ( child == 0 ) { ... execv( program, args ); } wait( &status ); 

and this structure should be a keeper, I do some things with it (redirecting stdin / out, measuring runtime, etc.)

My question is: how can I set a memory limit for a software process and tell my parents if it has been exceeded? A process should not be killed with siggs, I want to know that this process was killed only because of this memory limitation. Or better, is there a way to get the memory usage of this process when it finishes? At the end of the process, I can compare the maximum memory used.

I cannot use valgrind (or something like that) because I cannot slow down the runtime.

+6
source share
3 answers

You can call setrlimit() after checking for the child process and before calling execv() . I do not know how to notify the parent, but perhaps this will point you in the right direction.

+3
source

you can call ulimit inside a system (or setrlimit , as written by Mike). When your program reaches this limit, malloc will not work (i.e., returns NULL), and you will have to handle this situation (either they exit with an error or die with SIGSEGV if they try to access the null pointer).

About the parent signal ... Can you change the child program? You can return a specific exit code.

+1
source

Write your own memory manager to solve this problem.

For many applications written for morden OS, libc malloc / free is fine, but applications need great memories, they cannot determine how much memory our program used. We can write a structured memory tree context class that is the shell of glibc malloc / free, when we allocate some memory, load the memory used in this memory context, and when we free some memory, minus the value from the reserved value. Therefore, we can determine the size of the memory that we actually used.

+1
source

Source: https://habr.com/ru/post/946362/


All Articles