現代 Linux 核心 (2.6+) 支援將 initramfs 直接內建於核心映像 (vmlinuz/bzImage) 中,免除外部 initrd 檔案。核心配置選項:CONFIG_INITRAMFS_SOURCE (General Setup → Initramfs source file(s))。
.cpio 副檔名必要,核心以此識別)。initramfs.gz,先 gunzip 解壓再指定。/home/user/initramfs-tree)。/init (啟動程式)、/dev/console 等必要裝置節點。描述檔以文字定義檔案系統結構,語法:
# 註解
type name location mode uid gid [dev_type major minor] [link_target]
type: file | dir | nod | slink | pipe | sock
dir /dev 0755 0 0
nod /dev/console 0600 0 0 c 5 1
file /init /home/wyk/initramfs-test/hello_static 0755 0 0
dir:建立目錄。nod:建立裝置節點 (c=字元裝置, b=區塊裝置),需指定 major/minor 號。file:將主機檔案複製進映像,location 為主機路徑。slink:符號連結,link_target 為目標路徑。在核心配置指定此描述檔,編譯時自動構建 initramfs,效果等同方法二。
// hello.c
#include
#include
int main() {
printf("hello world, from initramfs.\n");
sleep(9999999); // 防止 kernel panic
return 0;
}
# 靜態編譯 (無外部依賴)
gcc -static -s -o hello_static hello.c
# 建構目錄法
mkdir -p image/{dev,proc,sys}
cp hello_static image/init
mknod -m 600 image/dev/console c 5 1 # 需 root
# 核心配置:CONFIG_INITRAMFS_SOURCE="/path/to/image"
# 需啟用:CONFIG_BINFMT_ELF=y (支援 ELF 執行檔)
編譯後核心映像自帶 initramfs,啟動即進入 hello world 環境,適合嵌入式、救援、無磁碟啟動場景。