Why can't I remove a cgroup?

Nicky Chorley ndchorley at gmail.com
Tue Aug 9 14:30:58 EDT 2022


Hi folks,

I wrote a small program to start a new process (a shell), create a
cgroup and add the process to it. This all works fine - the process ID
of the shell ends up in the cgroup.procs file and when my program
exits, cgroup.procs ends up empty as expected. If I try and remove the
cgroup directory, though, I get a load of "Operation not permitted"
errors and I'm not sure why. I'm running on openSUSE (kernel 5.3.18)
with cgroups v2.

My program looks like:

#define _GNU_SOURCE
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

int startShell(void *argument) {
    char* arguments[] = {"bash", NULL};
    char* environment[] = {NULL};
    execve("/bin/bash", arguments, environment);

    return 0;
}

int main() {
    mkdir(
        "/sys/fs/cgroup/my_group",
        S_IRWXO | S_IRGRP | S_IROTH
    );

    int stackSizeBytes = 65536;
    char *stackStart = malloc(stackSizeBytes);
    char *stackEnd = stackStart + stackSizeBytes;

    pid_t childPid = clone(
        startShell,
        stackEnd,
        SIGCHLD,
        NULL
    );

    FILE* procsFile = fopen(
        "/sys/fs/cgroup/my_group/cgroup.procs",
        "w"
    );

    fprintf(procsFile, "%d\n", childPid);
    fclose(procsFile);

    waitpid(childPid, NULL, 0);

    return 0;
}

and output looks like:

$ su -c ./run
Password:

# echo $$
4382
# cat /sys/fs/cgroup/my_group/cgroup.procs
4382
4522
# exit
$ cat /sys/fs/cgroup/my_group/cgroup.procs
$ su -c "rm -rf /sys/fs/cgroup/my_group"
Password:
rm: cannot remove '/sys/fs/cgroup/my_group/cgroup.events': Operation
not permitted
rm: cannot remove '/sys/fs/cgroup/my_group/memory.events': Operation
not permitted
... other lines omitted for brevity

Could someone please help me understand what's going on here?

Thanks!



More information about the Kernelnewbies mailing list