萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

將 init 程式打包進核心:從 Hello World 到可啟動 initramfs 完整實作

實作步驟:最小 initramfs 建構

1. 撰寫靜態 init 程式

// hello.c
#include 
#include 
int main(int argc, char *argv[]) {
    printf("hello world, from initramfs.\n");
    sleep(9999999);  // 防止 init 結束導致 kernel panic
    return 0;
}

靜態編譯 確保無動態庫依賴:

gcc -static -s -o hello_static hello.c
# -s: 去除除錯符號,減小體積

2. 建構 initramfs 目錄樹


mkdir -p image/{dev,proc,sys}
cp hello_static image/init          # 必須命名為 init
mknod -m 600 image/dev/console c 5 1  # 主控台裝置節點,需 root

3. 核心配置關鍵選項

  • General Setup → Initramfs source file(s):填入 image 目錄絕對路徑。
  • Executable file formats → Kernel support for ELF binaries:CONFIG_BINFMT_ELF=y,支援 ELF 格式 init。
  • 其他選項依硬體需求啟用 (如 SATA、USB、檔案系統驅動)。

4. 編譯與驗證


make bzImage   # 或 make
# 編譯完成的 arch/x86/boot/bzImage 已內建 initramfs
# 使用 QEMU 或實體機測試:
qemu-system-x86_64 -kernel arch/x86/boot/bzImage -nographic

啟動畫面將顯示 hello world, from initramfs. 並停留於 sleep,證明 initramfs 成功載入並執行 init。

進階擴展方向

  • 將 init 替換為 Shell 腳本 (#!/bin/sh),呼叫 mount、mdev、switch_root 切換真實根檔案系統。
  • 加入 busybox 提供完整指令集。
  • 整合 udev/mdev 自動建立裝置節點。
  • 支援核心模組載入 (insmod/modprobe) 掛載真實根裝置。

此最小實作展示了 initramfs 核心機制:核心解壓內建 cpio → 執行 /init (PID 1) → 由用戶空間接管後續啟動流程。

copyright © 萬盛學電腦網 all rights reserved