C Program on Linux to exhaust memory

前端 未结 10 694
孤独总比滥情好
孤独总比滥情好 2020-12-24 03:06

I would like to write a program to consume all the memory available to understand the outcome. I\'ve heard that linux starts killing the processes once it is unable to alloc

10条回答
  •  遥遥无期
    2020-12-24 03:17

    A little known fact (though it is well documented) - you can (as root) prevent the OOM killer from claiming your process (or any other process) as one of its victims. Here is a snippet from something directly out of my editor, where I am (based on configuration data) locking all allocated memory to avoid being paged out and (optionally) telling the OOM killer not to bother me:

    static int set_priority(nex_payload_t *p)
    {
        struct sched_param sched;
        int maxpri, minpri;
        FILE *fp;
        int no_oom = -17;
    
        if (p->cfg.lock_memory)
            mlockall(MCL_CURRENT | MCL_FUTURE);
    
        if (p->cfg.prevent_oom) {
            fp = fopen("/proc/self/oom_adj", "w");
            if (fp) {
                /* Don't OOM me, Bro! */
                fprintf(fp, "%d", no_oom);
                fclose(fp);
            }
        }
    

    I'm not showing what I'm doing with scheduler parameters as its not relevant to the question.

    This will prevent the OOM killer from getting your process before it has a chance to produce the (in this case) desired effect. You will also, in effect, force most other processes to disk.

    So, in short, to see fireworks really quickly...

    1. Tell the OOM killer not to bother you
    2. Lock your memory
    3. Allocate and initialize (zero out) blocks in a never ending loop, or until malloc() fails

    Be sure to look at ulimit as well, and run your tests as root.

    The code I showed is part of a daemon that simply can not fail, it runs at a very high weight (selectively using the RR or FIFO scheduler) and can not (ever) be paged out.

提交回复
热议问题