WSL2 无法使用图形界面的解决方法

WSL2 无法使用图形界面的解决方法

Windows 版本

打开命令提示符(不是 PowerShell )输入 ver,会有如下输出:

Microsoft Windows [版本 10.0.26100.2605]

Windows 版本必须在 21364 以上 WSLg 才能工作。

DISPLAY 环境变量

进入 WSL 的终端,输入 echo $DISPLAY 查看 DISPLAY 环境变量:

❯ echo $DISPLAY
:0

WSLg 的 X server 在 display 0 上运行,所以 DISPLAY 环境变量的值必须为 :0

X11 display socket 文件链接

X servers 在 /tmp/.X11-Unix 下创建 socket ,该目录必须存在且链接到 /mnt/wslg/.X11-Unix

使用 ls -la /tmp/.X11-unix 命令查看文件信息:

❯ ls -la /tmp/.X11-unix
lrwxrwxrwx 1 root root 19 Dec 19 08:30 /tmp/.X11-unix -> /mnt/wslg/.X11-unix

结尾的 /tmp/.X11-unix -> /mnt/wslg/.X11-unix 表明文件是正常链接状态。

而像下面这种输出,就表明文件没有正常链接:

❯ ls -la /tmp/.X11-unix
lrwxrwxrwx 1 root root 19 Dec 19 08:30 /tmp/.X11-unix

此时,我们可以通过以下命令重新创建链接:

# 手动创建链接,WSL 每次重启都要重新输入
# 稍后会介绍自动创建链接的方法
sudo rm -r /tmp/.X11-unix                   # 删除未链接的文件
ln -s /mnt/wslg/.X11-unix /tmp/.X11-unix    # 重新创建文件链接

如果 X server 正在运行,你应该能在 /tmp/.X11-unix 目录下看到一个 X0 套接字:

❯ ls /tmp/.X11-unix/
X0

为了避免 WSL 重启后又要手动输入一遍链接命令,我们可以使用 systemd 配置自动化运行文件。

因为 socket 文件链接在 /tmp 目录下,而 systemd 可以通过 /etc/tmpfiles.d/ 中的配置文件管理 /tmp 目录。

所以,我们创建一个新的配置文件 /etc/tmpfiles.d/wslg.conf 写入以下内容:

#  This file is part of the debianisation of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

# See tmpfiles.d(5) for details

# Type Path           Mode UID  GID  Age Argument
L+     /tmp/.X11-unix -    -    -    -   /mnt/wslg/.X11-unix

该方法来自:https://github.com/microsoft/wslg/issues/43#issuecomment-826039096

忽略 # 开头的注释,真正内容只有最后一行,就是创建 /tmp/.X11-unix/mnt/wslg/.X11-unix 的文件链接。

这样一来, WSL 重启时就能自动创建 socket 文件链接了。

参考资料

Diagnosing "cannot open display" type issues with WSLg · microsoft/wslg Wiki

Init /tmp/.X11-unix is overwritten by mounts · Issue #43 · microsoft/wslg


本文发布于2024年12月19日

最后修改于2024年12月19日

posted @   千松  阅读(632)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示