initrd: 并不是我们实际看到的 Linux

只是一个内存里的小文件系统

  • 我们 “看到” 的都是被 init 创造出来的
    • 加载剩余必要的驱动程序,例如网卡
    • 根据 fstab 中的信息挂载文件系统,例如网络驱动器
    • 将根文件系统和控制权移交给另一个程序,例如 systemd

构建一个 “真正” 的应用世界

int pivot_root(const char *new_root, const char *put_old);
  • pivot_root() changes the root mount in the mount namespace of the calling process. More precisely, it moves the root mount to the directory put_old and makes new_root the new root mount. The calling process must have the CAP_SYS_ADMIN capability in the user namespace that owns the caller's mount namespace.
  • 执行 /usr/sbin (Kernel 的 init 选项)
    • 看一看系统里的文件是什么吧
    • 计算机系统没有魔法 (一切都有合适的解释)

例子:NOILinux Lite

在 init 时多做一些事

export PATH=/bin
busybox mknod /dev/sda b 8 0
busybox mkdir -p /newroot
busybox mount -t ext2 /dev/sda /newroot
exec busybox switch_root /newroot/ /etc/init
  • pivot_root 之后才加载网卡驱动、配置 IP
    • 这些都是 systemd 的工作
    • (你会留意到 tty 字体变了)
  • 之后 initramfs 就功成身退,资源释放