检查 WSL 版本(1 或 2)*在 Linux 安装中*

luc*_*svc 3 windows-subsystem-for-linux wsl2

You can check which version is each installed distribution with the command,

wsl -l -v
Run Code Online (Sandbox Code Playgroud)

as this superuser question states.

But is it possible to know the WSL version (1 or 2) from inside the Linux installation?

Is there any reliable mechanism to check the version?

What I found?

Environment and "interop"

The only difference in environment variables, is that WSL 2 has one named WSL_INTEROP that version 1 has not.

That variable points to a path special file.

Kernel version

This reddit post reply points to use the following command,

uname -r | tr '[:upper:]' '[:lower:]'
Run Code Online (Sandbox Code Playgroud)

WSL 1 output:

4.4.0-19041-microsoft
Run Code Online (Sandbox Code Playgroud)

WSL 2 output:

5.4.72-microsoft-standard-wsl2
Run Code Online (Sandbox Code Playgroud)

Could this be an option except the replies given,

Probably better not to go with a kernel check as you can build and install your own kernel, and some people would strip that out.

虽然这个askubuntu接受的答案指出

如果内核版本 => 4.19,则为 WSL 版本 2。

还有其他选择/想法吗?

附录github/WSL 存储库有问题 #4555

Not*_*1ds 5

我想我更喜欢@DuncG 的答案。我认为它可能失败的唯一方法是如果Interop/etc/wsl.conf. 只要您确信互操作始终处于打开状态,这似乎就是可行的方法。

但我要补充一点,WSL1 和 WSL2 之间存在相当多的差异,可以用作分类。


假设您正在使用 Windows 驱动器的自动挂载:

  • mount | grep "/mnt/c" | grep -q drvfsWSL1 返回成功,WSL2 返回失败
  • mount | grep "/mnt/c" | grep -q 9pWSL2 返回成功,WSL1 返回失败

另外lscpu,但默认情况下 Alpine 中缺少此命令(当然,在 Ubuntu 和 Kali 上可用,我假设在 Debian 上):

  • lscpu | grep -q "Hypervisor vendor:.*Microsoft"将在 WSL2 上成功,但在 WSL1 上失败,因为只有 WSL2 在 Hyper-V 下运行。

我对此不是 100% 确定,但在我测试的每种情况下(WSL1 和 WSL2 上的 Ubuntu 20.04、WSL1 和 WSL2 上的 Kali、WSL1 和 WSL2 上的 Alpine):

  • /proc/cmdline在 WSL1 上是BOOT_IMAGE=/kernel init=/init
  • /proc/cmdline在 WSL2 上是initrd=\initrd.img panic=-1 pty.legacy_count=0 nr_cpus=16 (更新说明:最近支持 Systemd 的 WSL2 版本稍微改变了这一点。当然,使用.wslconfig设置内核命令行参数也会改变这一点。但是,下面的示例在这两种情况下仍然有效。)

所以:

  • grep -q "^BOOT_IMAGE" /proc/cmdline在 WSL1 上返回成功,但在 WSL2 上返回错误
  • grep -q "^initrd" /proc/cmdline在 WSL2 上返回成功,但在 WSL1 上返回错误

我确信还有其他的,但如果您需要的话,这些都是一些可能性。

  • 真的很棒的工作。也许我们可以使用这些信息创建一个 shell。然而,我认为有很多边界情况需要考虑。例如,您可以更改“wsl.conf”中的“/mnt/c”挂载点。如果您也运行重量级虚拟机,则可能会出现虚拟机管理程序签名。我认为完整的解决方案需要结合多种检查。 (2认同)