WSL2下使用systemd的最佳方案

本教程基于WSL2,参考:ArchWSL Known issues

ArchWSL Known issues中,有几种推荐的systemd容器,分别是“subsystemctl”, “genie”, “wsl-distrod” or “bottled-shell”,其中我比较推荐的就是“wsl-distrod”,本教程也是基于此展开。

wsl-distrod的安装方法参考他的项目主页,发行版可以选择自己喜欢的,我推荐Ubuntu,对WSL适配比较好

安装完进入系统后,就已经可以使用systemd了

fd7adc4080ae6bb66ac289b8e48c94b3/20230318173810.png

但是systemctl status –user 不能正常工作,wslg也不能使用wayland

9f2012704b13c4704181ff4bb492589f/20230318173826.png

因为distrod安装的Ubuntu有一个问题,在你新建用户后,/mnt/wslg/runtime-dir的权限是属于用户ubuntu的,这个文件夹即XDG_RUNTIME_DIR其他用户无法访问,wayland程序的运行也需要访问runtime-dir,你可以直接把runtime-dir的权限改为777,虽然不符合$XDG_DATA_HOME - XDG Base Directory Specification的要求,但是这样其他用户就可以访问了,wayland也就可以正常工作。

这样做用户的dbus依然不能运行,因为他要求runtime-dir 的权限必须为700。

bdb4244187e9eb5a54412808e42e0a6d/20230318173858.png

为了解决这个问题,最好的思路就是把XDG_RUNTIME_DIR设置为默认的/run/user/uid目录(wsl2中,该变量为/mnt/wslg/runtime-dir),然后正确设置权限;

首先,用loginctl enable-linger $(id -u),系统会创建/run/user/uid目录,最后把wayland链接到该目录中(保证用户正常使用wayland)

编写一个完成这些任务的脚本 sudo vi /bin/update-runtime-dir,并给予可执行权限 sudo chmod +x /bin/update-runtime-dir

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#! /bin/bash

ln-runtime-dir() {
# 获取系统所有的uid
UIDS=($(awk -F: '{if ($3 >= 0) {printf "%s\n", $3}}' /etc/passwd))

for id in ${UIDS[@]}
do
loginctl enable-linger $id
ln -s /mnt/wslg/runtime-dir/wayland* /run/user/$id
done
}

while :; do
sleep 1;
chmod 777 -R /mnt/wslg/runtime-dir;
ln-runtime-dir;
done

编写一个systemd服务 sudo vi /lib/systemd/system/update-runtime-dir-d.service

1
2
3
4
5
6
7
8
[Unit]
Description=Fix runtime-dir

[Service]
ExecStart=/usr/bin/update-runtime-dir

[Install]
WantedBy=multi-user.target

然后启用该systemd服务 sudo systemctl enable --now update-runtime-dir-d

6fd94d2ae4605113f397f36e095ac3a3/20230318173934.png

修改 ~/.bashrc,如果是zsh则修改 ~/.zshrc , 在最后添加 export XDG_RUNTIME_DIR="/run/user/$(id $USER -u)"

执行 wsl -t Distrod终止该发行版,然后执行 wsl -d Distrod运行

这时就可以使用 systemctl status --user

7b2088e7a720fba920288a847a23fb3f/20230318174002.png

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2021-2025 lorzzn
  • 访问人数: | 浏览次数:

      请我喝杯咖啡吧~

      支付宝
      微信