Search code examples
cfork

How to keep forking a process until I "almost" run out of memory


I want to keep forking a process until I'm almost out memory. How Do I know how many times I can fork a process without crashing?


Solution

  • Here is program to calculate estimate (using Linux API's):

    #include <sys/resource.h>
    #include <sys/sysinfo.h>
    #include <stdio.h>
    
    unsigned long maxmem() {
        struct sysinfo info;
        if (sysinfo(&info) < 0)
            return 0;
        return info.freeram;
    }
    
    long getmem(void) {
        struct rusage r_usage;
        getrusage(RUSAGE_SELF,&r_usage);
        return r_usage.ru_maxrss;
    }
    
    int main() {
        printf("Can fork %d times. Mfm: %d, upp: %d\n", maxmem() / 1024 / getmem(), maxmem() / 1024, getmem());
        return 0;
    }
    

    Please note that this is just an estimate, you may need to run this code inside your application when it reaches peak memory usage.