WSL2的Linux安装与使用
开宗明义
不推荐wsl1转制成wsl2
原因就是再转制的过程中 文件的mode属性会丢失
也不推荐相互转 因为文件系统不同 所以属性存储的位置是不一样的
依赖条件
- Windows 10 build 18917 及其更高版本
- Windows Subsystem for Linux 组件开启
- Virual Machine Platform 组件开启
先行设置
# 开启 Windows Subsystem for Linux
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
# 开启 Virual Machine Platform
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
# (可选) 设置wsl默认版本
wsl --set-default-version 2
安装系统
不推荐从 Windows Store 下载相关发行版
我们使用 wsl.exe 手动部署
首先准备发行版 tar 包
| 发行版 | 版本 | 下载相关 |
|---|---|---|
| Ubuntu | 18.04(Bionic) | tar.gz |
| Gentoo | v0.1-alpha1 | tar |
| Gentoo amd64 nomultilib | — | tar |
| ArchLinux | 20.2.7.0 | zip |
# 导入系统
wsl --import <Distro> <InstallLocation> <FileName> --version 2
导入完成之后 之后要做以下几个操作
# 设置密码
passwd root
# 创建新用户 ubuntu 没有 wheel 组; gentoo/ArchLinux 没有 sudo 组
useradd -m -G users,wheel,sudo,audio -s /bin/bash <UserName>
passwd <UserName>
# 获取用户id
id -u <UserName>
# 设置默认用户
# 获取 UUID
Get-ChildItem -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss\ | Get-ItemProperty |Select-Object -Property DistributionName,PSChildName
# PSChildName 显示的就是 distro-UUID
DistributionName PSChildName
---------------- -----------
gentoo {642d335d-f7ad-46bb-9c11-fdee96b4644f}
Gentoo {96173873-9dd2-4971-8f30-64aba57cd4dd}
ArchLinux {b8690f59-f6e3-4eea-bd44-b16893f4cbc5}
Ubuntu {e566c16a-b047-46da-ae71-880838d384ab}
# 进入注册表
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Lxss\{distro-UUID}
# 修改DefaultUid
设置 DefaultUid 为 上一步获取的 id
这样子操作之后 wsl2 就以新建的用户启动了
当然也可以设置其他的注册表项
| 注册表项名 | 值意义 |
|---|---|
BasePath | rootfs的路径 |
DefaultUid | 默认登陆用户的UID |
DistributionName | 发行版名称 |
DefaultEnvironment | 环境变量设置 |
KernelCommandLine | Kernel与init设置 |
DefaultEnvironment 的一个参考设置
HOSTTYPE=x86_64 LANG=en_US.UTF-8 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
KernelCommandLine 的一个参考设置
BOOT_IMAGE=/kernel init=/init
自定义内核
安装一个最新的Ubuntu系统
# 下载ms定制内核
cd ~/workspaces
git clone -b linux-msft-wsl-5.4.y https://github.com/microsoft/WSL2-Linux-Kernel.git
cd WSL2-Linux-Kernel
# 多核编译定制内核 推荐编译5.4.x
sudo apt install build-essential flex bison libssl-dev libelf-dev
make KCONFIG_CONFIG=Microsoft/config-wsl -j`nproc`
rm -rf /mnt/c/kernel/vmlinux
cp vmlinux /mnt/c/kernel/vmlinux
# 4.19.x在gcc-10下有编译错误
# arch/x86/boot/compressed/kaslr_64.c:33 增加 extern
# Gentoo
sudo emerge -av elfutils bc
配置wslconfig
编辑 %USERPROFILE%/.wslconfig
[wsl2]
kernel=C:\\kernel\\vmlinux # 设置自定义内核
memory=32GB # 限制内存大小
#processors= # 限制wsl2处理器数量
#swap=
#swapFile=
localhostForwarding=true # 允许本地转发