为什么 Windows Subsystem for Linux 能够运行 Windows *.exe 程序?

Dan*_*tos 8 windows windows-10 windows-subsystem-for-linux

我在 Windows 10 Home 上使用新的 WLS2。我注意到,当我运行“npm”时,执行的是 Windows 程序文件中的“npm”,而不是 Linux 版本。

当我尝试从 WSL2 执行 cmd.exe 或 notepad.exe 时,我注意到它们也有效!

这怎么可能?WSL2 如何运行 Windows 可执行文件?

此外,如果它们具有相同的名称,我如何强制 WSL2 将 Linux 可执行文件优先于 Windows 可执行文件?

Bis*_*iyo 10

WSL2 如何运行 Windows 可执行文件?

Windows 可执行文件(PE 二进制文件)作为binfmt_misc条目添加到 WSL2 中。简单来说,binfmt_misc是一个 Linux 内核特性,它允许识别任意可执行文件格式并将其传递给某些程序。

在 WSL2 中,init二进制文件(从中派生出每个进程)将 Windows PE 二进制文件注册为可执行文件并使其自身可执行(即init)。这是 PE binfmt 条目的输出:

cat /proc/sys/fs/binfmt_misc/WSLInterop
enabled
interpreter /tools/init
flags: F
offset 0
magic 4d5a
Run Code Online (Sandbox Code Playgroud)

WSLInterop只是条目的名称。幻数4d5aMZWindows PE 可执行文件的前两个字节。假设这是init(解释器)用来识别 PE 二进制文件的指纹。

用户可以使用以下命令禁用注册表:

echo 0 | sudo tee /proc/sys/fs/binfmt_misc/WSLInterop
Run Code Online (Sandbox Code Playgroud)

进一步阅读:


Chr*_*odd 6

它将运行$PATH环境变量中的任何可执行文件(Windows 或 linux)。它按顺序搜索目录,因此如果您想按偏好运行 linux 版本,请确保这些目录位于路径中的 windows 目录之前

  • 因为最终您仍在运行 Windows。虽然 WSL 2 运行的是 Linux 内核,但它知道 Windows。 (4认同)

小智 5

bash 作为 pico 进程运行。当您尝试运行程序时,Linux 子系统驱动程序会识别运行进程的请求并调用ZwCreateUserProcessWindows 内核,创建 Windows 进程。

它可以调用该函数,因为 pico 进程进行的所有系统调用都被翻译为内核模式下的 NT 调用,无论是通过LXCORE.SYS还是内核ntoskrnl.exe