导读:“用户态 Linux” 是什么?它是一种可以在用户态运行的 Linux 内核。
本文字数:3032,阅读时长大约: 3分钟
https://github.com/LCTT/Articles/pull/8
作者:Calvinlin
“用户态 Linux” 是什么?它是一种可以在用户态运行的 Linux 内核。(用户态是什么,这里就不解释了)
它有什么用?它用于内核隔离、替代 QEMU/Bochs 来调试 Linux 内核,也可以在低性能设备上代替 KVM 进行虚拟化。
但它也存在一些缺陷,比如不支持 ARM 架构以及多核系统。
编译 Linux 内核
首先通过 下载 Linux 内核源代码:
git clone --depth 1 https://mirrors.tuna.tsinghua.edu.cn/git/linux.git
(这里使用了清华大学的镜像站, kernel.org 也是可以的。)
然后采用如下步骤编译它:
$ cd linux$ export ARCH=um # 非常重要 设置架构为用户态$ make defcongig$ make -j8LD .tmp_vmlinux.kallsyms1KSYMS .tmp_vmlinux.kallsyms1.SAS .tmp_vmlinux.kallsyms1.SLD .tmp_vmlinux.kallsyms2KSYMS .tmp_vmlinux.kallsyms2.SAS .tmp_vmlinux.kallsyms2.SLD vmlinuxSYSMAP System.mapLINK linuxMODPOST modules-only.symversGEN Module.symvers
经过漫长的编译之后,你获得了一个vmlinux文件。它和正常的 Linux 内核的区别是,这个vmlinux可以在用户态运行。
准备根文件系统
先别着急启动,先来准备内核所使用的根文件系统。
以下内容以 Debian Linux 为例。
首先安装 软件包:
sudo apt install debootstrap
以下命令皆需要 root 权限,先切换到 root 用户:
$ sudo su
然后构建根文件系统,存放在rootfs文件中:
# dd if=/dev/zero of=rootfs seek=2G # 创建一个 2GB 大小的空 rootfs 文件2000000000字节(2 GB,2 GB)已复制,0.137825 s,570 MB/s`# mkfs.ext4 rootfs # 将其格式化为 ext4 格式mke2fs 1.46.5 (30-Dec-2021)Discarding device blocks: doneCreating filesystem with 76748 1k blocks and 19200 inodesFilesystem UUID: 9dc7f1f6-8b16-4c64-9e22-94ede327c532Superblock backups stored on blocks:8193, 24577, 40961, 57345, 73729Allocating group tables: doneWriting inode tables: doneCreating journal (4096 blocks): doneWriting superblocks and filesystem accounting information: done
然后挂载rootfs到/mnt下:
# mount rootfs /mnt
在其中创建 Debian Linux 的根文件系统(/):
# cd /mnt# debootstrap sid ./ https://mirrors.tuna.tsinghua.edu.cn/debianI: Configuring python-central...I: Configuring ubuntu-minimal...I: Configuring libc-bin...I: Configuring initramfs-tools...I: Base system installed successfully.
通过 将其改变为根目录:
# chroot ./
设置 root 密码:
# passwdNew password:Retype new password:
然后退出 chroot 环境,并卸载:
# exit # 退出 chroot 环境# cd ..# umount /mnt# exit # 退出 sudo 环境
设置 rootfs 的所有权为普通用户:
$ sudo chown `whoami` rootfs
这样,这个用户态 Linux 的根文件系统就准备好了。
测试用户态 Linux
然后就可以用这个内核启动了,只需要一行命令:
$ screen ./vmlinux mem=1G root=/dev/root rootfstype=hostfs hostfs=./rootfs con=null con0=null,fd:2 con1=fd:0,fd:1
启动后,使用你前面设置的 root 用户/密码登录,便可以进入到用户态 Linux 容器中了。
有别于 Docker,这个容器的内核和宿主的内核是隔离的,可以使用这个容器作为一个调试内核的工具,如:
echo 1 > /proc/sys/kernel/sysrqecho c > /proc/sysrq-trigger
即可手动触发一个“内核恐慌(Kernel Panic)”错误。
作者简介:
calvinlin:一个普通的深圳初中生。
via:
作者: 编辑:
本文由贡献者投稿至 ,采用 发布, 荣誉推出
欢迎遵照 CC-BY-SA 协议规定转载,
如需转载,请在文章下留言 “ 转载:公众号名称”,
我们将为您添加白名单,授权“ 转载文章时可以修改”。
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.