操作系统原理 2026

BusyBox:从空白系统开始

原片 01:05:16—01:10:58

接着实际看 Linux。我准备了两份都叫 init 的脚本,名字容易混淆,但内容不同。先看 initramfs 阶段:这里只有 BusyBox,可以加一个 shell。这个例子打包的初始文件系统中有 /init。

还有 /bin/busybox 和一些驱动。今天发现 QEMU 必须有这些驱动才能正确运行,就一起打包进 initramfs,此外没有别的内容。Linux 加载后,会解开 initramfs,将它作为文件系统,再执行里面的 init。

图 80:initramfs 中的 init 删除自己并启动 shell(01:06:40)。
图 80:initramfs 中的 init 删除自己并启动 shell(01:06:40)。

init 的开头:

#!/bin/busybox sh

# At this point, we only have:
#   /bin/busybox - the binary
#   /dev/console - the console device
BB=/bin/busybox

# Delete this file
# (Yes, we can do this on UNIX! The file is "removed"
# after the last reference, the fd, is gone.)
$BB rm /init

$BB sh
图 81:初始文件系统中的 init 与 BusyBox(01:06:40)。
图 81:初始文件系统中的 init 与 BusyBox(01:06:40)。

init 的解释器是 /bin/busybox sh,用 shell 解释脚本。它先删掉 /init,再启动一个 shell。编译、运行后,这次会出现图形界面。我用树莓派做全系统模拟,速度稍慢。

图 82:QEMU 启动命令与 KVM 不可用警告(01:07:01)。
图 82:QEMU 启动命令与 KVM 不可用警告(01:07:01)。

x86-64 的 QEMU 可能需要几秒才能启动。随后 Linux 正常运行,加载 initramfs,刚才的脚本也开始执行。

图 83:只有 BusyBox 的初始 shell(01:07:15)。
图 83:只有 BusyBox 的初始 shell(01:07:15)。

脚本启动后,用 find / 看,系统里只有 /bin/busybox、后续操作必需的一批驱动,以及 /dev/console。还有 /root,是 shell 创建的,最初并没有。

图 84:初始文件系统中的 BusyBox、驱动与 console(01:07:33)。
图 84:初始文件系统中的 BusyBox、驱动与 console(01:07:33)。

/bin/ls、/bin/sh 等二进制文件都不存在,只有 /bin/busybox。脚本尚未结束,现在运行到 13 行,停在 shell。退出后,会先打印一条 message,再执行一段脚本:for cmd in busybox --list。可以看一下 /bin/busybox --list,它列出 BusyBox 支持的全部命令。这么多功能都集成在一个二进制文件中。脚本会为它们创建符号链接。

例如 command 是 ls,就执行 BusyBox 的 ln,让 /bin/ls 链接到 BusyBox。三行脚本就能在 /bin 下创建一大批命令文件。

图 85:创建命令符号链接及挂载 procfs、sysfs(01:08:57)。
图 85:创建命令符号链接及挂载 procfs、sysfs(01:08:57)。

创建命令入口并挂载 procfs、sysfs:

for cmd in $($BB --list); do
    $BB ln -s $BB /bin/$cmd
done

mkdir -p /proc && mount -t proc  none /proc
mkdir -p /sys  && mount -t sysfs none /sys

接着用 mkdir、mount 创建操作系统对象,包括 procfs 和 /sys;用 insmod 安装一批驱动;用 mknod 创建设备。最后打印 init-ok。

还有 Launch a shell、initramfs、busybox sh。现在退出当前 shell,脚本就继续完成剩余操作,打印这些日志。可以看到 insmod 成功,以及红色的 init-ok、Launch a shell、initramfs。

图 86:创建设备并进入初始化后的 shell(01:09:42)。
图 86:创建设备并进入初始化后的 shell(01:09:42)。
图 87:Init OK 后的第二个 shell(01:09:51)。
图 87:Init OK 后的第二个 shell(01:09:51)。

这时 procfs 已有内容,可以运行 ps。ls /bin 会列出现在的功能:每个文件都是指向 /bin/busybox 的符号链接,包括 word count,还有处理互联网功能的 wget。

图 88:初始化后出现的 proc、sys 和 modules(01:10:06)。
图 88:初始化后出现的 proc、sys 和 modules(01:10:06)。
图 89:由 BusyBox 提供的命令列表(01:10:12)。
图 89:由 BusyBox 提供的命令列表(01:10:12)。
图 90:命令路径指向 BusyBox 的符号链接(01:10:17)。
图 90:命令路径指向 BusyBox 的符号链接(01:10:17)。

系统已经有些可用了。有 pstree 吗?没有,只有 ps。ps 显示一号进程是 init,即 busybox sh /init,是 initramfs 阶段最早由操作系统加载的二进制文件,也是所有进程的祖先。还有一些操作系统自己的线程。

图 91:ps 中的 PID 1:busybox sh /init(01:10:33)。
图 91:ps 中的 PID 1:busybox sh /init(01:10:33)。

除此以外,就只有当前 busybox sh 和刚才运行的 ps。

图 92:ps 中的内核线程与当前 shell(01:10:51)。
图 92:ps 中的内核线程与当前 shell(01:10:51)。

输入关键词,搜索全部 30 节课。