3

I'm on Debian Bullseye (hence cgroups v2, afaik) and I'm trying to use systemd-run to limit the memory usage of a process. I need the process to be killed when it goes out of memory (I'm setting up some benchmarks).

This is the test program:

#include <stdio.h>
#include <stdlib.h>

int main() {
    const size_t size = 1024 * 1024 * 1024;
    int *buffer = (int*)malloc(size * sizeof(int));

    int v = 0;
    for(size_t i = 0; i < size; ++i) {
        buffer[i] = v++;
    }

    printf("Hello\n");

    while(1);

    return 0;
}

It allocates 4Gb of memory and goes on an infinite loop. To be sure pages are really allocated (I don't know if it matters) the program writes on the memory after the allocation.

I'm trying to run it with systemd-run as follows:

$ systemd-run --quiet  --user --scope -p MemoryMax=500M ./test

However, the program prints Hello and is not killed.

What am I doing wrong?

1 Answer 1

3

I needed to add the MemorySwapMax argument to also give a zero limit to swap usage, otherwise the program would use swap space to overcome the MemoryMax argument.

The correct command line is the following:

$ systemd-run --quiet --user --scope -p MemoryMax=500M -p MemorySwapMax=0 ./test
1
  • 1
    Additionally, for MemorySwapMax to work, you need to make sure you have cgroups v2 enabled for instance by using the systemd.unified_cgroup_hierarchy=yes kernel parameter. You can check this using grep cgroup /proc/self/mountinfo which should output only one line containing cgroup2.
    – faxmodem
    Commented Mar 7 at 13:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .