Initramfs 原理和实践(2)

可以看到initramfs和跟分区文件系统的雏形很像,只是它的大小不大,少了很多工具和库。有些内核模块就在其中,比如:/lib/modules/4.4.0-93-generic/kernel/。

qemu中启动"Hello World" initramfs

在前文“在QEMU环境中使用GDB调试Linux内核”中,已经准备了一个Linux启动环境,但是缺少initramfs。我们可以做一个最简单的Hello World initramfs,来直观地理解initramfs。

Hello World的C程序如下,与普通的Hello World相比,加了一行while(1)。

#include <stdio.h> void main() { printf("Hello World\n"); fflush(stdout); /* 让程序打印完后继续维持在用户态 */ while(1); }

编译helloworld.c程序

# gcc -static -o helloworld -m32 helloworld.c

在64位机器上编译成32位程序,可能会报错如下:

In file included from /usr/include/stdio.h:27:0,
from helloworld.c:2:
/usr/include/features.h:374:25: fatal error: sys/cdefs.h: No such file or directory
# include <sys/cdefs.h>
^
compilation terminated.

解决方案是安装libc6-dev-i386包。

# apt-get install libc6-dev-i386

打包initramfs文件

# echo helloworld | cpio -o --format=newc > hwinitramfs

在qemu中启动编译好的内核,把hwinitramfs指定为initrd,在-append参数中将init指定为helloworld。

# qemu -kernel linux-3.18.6/arch/x86/boot/bzImage -initrd hwinitramfs -append "console=ttyS0 rdinit=helloworld" -nographic

系统能成功启动到输出"Hello World",并且在用户态停住。结合前文“在QEMU环境中使用GDB调试Linux内核”,可以看到qemu虚机中运行的Linux系统已经成功挂载了initramfs, 在console日志中也能看到“Unpacking initramfs...”。

Initramfs 原理和实践

参考

Custom Initramfs

GNU CPIO Manual

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/12073.html