Using systemd with WSL2

Quite easy, download the systemd source package, skip the pid == 1 check, build and install, prepare some folders and then start systemd. Tada, mission accomplished.

The first time we need to do is to slightly change the source code of systemd to skip the annoying check, which required systemd to be the first process executed by the kernel. You may rely on apt source systemd and apt build-dep systemd commands.

Comment out the following lines in systemd-241/src/core/main.c,

if (getpid_cached() == 1 &&
        return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                "Can't run --user mode as PID 1.");

/*if (arg_action == ACTION_RUN &&
    arg_system &&
    getpid_cached() != 1)
        return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                "Can't run system mode unless PID 1.");*/

if (arg_action == ACTION_TEST &&
    geteuid() == 0)
        return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                "Don't run test mode as root.");

Then build the package with sudo DEB_BUILD_OPTIONS=nocheck dpkg-buildpackage -rfakeroot -b -uc -us command. Install the generated package with sudo dpkg -i systemd_241-7~deb10u7_amd64.deb command.

The last thing we need to do is to run systemd itself,

mkdir -p /run/systemd
mkdir -p /run/systemd/system
mount -o remount,rw /sys/fs/cgroup
mkdir /sys/fs/cgroup/systemd
mount -t cgroup -o none,rw,nosuid,nodev,noexec,relatime,name=systemd systemd /sys/fs/cgroup/systemd
/lib/systemd/systemd --system

You may put it somewhere like .bashrc to automatically check whether systemd is working in backgroup or not like,

if ! pgrep -x "systemd" > /dev/null
    echo "raise systemd"
    sudo mkdir -p /run/systemd
    sudo mkdir -p /run/systemd/system
    sudo mount -o remount,rw /sys/fs/cgroup
    sudo mkdir /sys/fs/cgroup/systemd
    sudo mount -t cgroup -o none,rw,nosuid,nodev,noexec,relatime,name=systemd systemd /sys/fs/cgroup/systemd
    sudo nohup /lib/systemd/systemd --system 2>&1 1>/dev/null &

Enjoy a fully functional linux distro.

Leave a Reply

Your email address will not be published. Required fields are marked *