转自:http://blog.csdn.net/lwbeyond/article/details/8444535
从kernel_init()函数我们知道,init_post是最后执行的一个函数,我们来分析这个函数:
-
static int noinline init_post(void)
-
{
-
free_initmem();
-
unlock_kernel();
-
mark_rodata_ro();
-
system_state = SYSTEM_RUNNING;
-
numa_default_policy();
-
-
-
if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
-
printk(KERN_WARNING "Warning: unable to open an initial console.
");
-
-
-
(void) sys_dup(0);
-
(void) sys_dup(0);
-
-
if (ramdisk_execute_command) {
-
run_init_process(ramdisk_execute_command);
-
printk(KERN_WARNING "Failed to execute %s
",
-
ramdisk_execute_command);
-
}
-
-
-
-
-
-
-
-
-
-
-
-
if (execute_command) {
-
run_init_process(execute_command);
-
printk(KERN_WARNING "Failed to execute %s. Attempting "
-
"defaults...
", execute_command);
-
}
-
-
-
run_init_process("/sbin/init");
-
run_init_process("/etc/init");
-
run_init_process("/bin/init");
-
run_init_process("/bin/sh");
-
-
panic("No init found. Try passing init= option to kernel.");
-
}
从上面可以看出如果执行命令里没有 init=xxx 的参数,那么就会依次向下执行
-
run_init_process("/sbin/init");
-
......
因为我们的执行命令里没有init=xxx参数,所以 init 就是我们的第一个进程。
但是如果我们执行下面的命令:
-
ls -l /sbin/init
-
lrwxrwxrwx 1 messageb messageb 14 Dec 21 2012 /sbin/init -> ../bin/busybox
我们发现第一个程序是链接到busybox的,也就是说启动是busybox程序,所以我们要分析busybox源码里的init.c源码。
打开 busybox 源码中的 init.c文件,分析int.c 是怎么解析 /etc/inittab 文件以及执行程序的:
-
init_main
-
parse_inittab
-
file = fopen(INITTAB, "r");
-
new_init_action
-
-
run_actions(SYSINIT);
-
waitfor(a, 0);
-
run(a);
-
waitpid
-
delete_init_action(a);
-
-
run_actions(WAIT);
-
waitfor(a, 0);
-
run(a);
-
waitpid
-
delete_init_action(a);
-
-
run_actions(ONCE);
-
run(a);
-
delete_init_action(a);
-
-
while (1) {
-
run_actions(RESPAWN);
-
if (a->pid == 0) {
-
a->pid = run(a);
-
}
-
-
run_actions(ASKFIRST);
-
if (a->pid == 0) {
-
a->pid = run(a);
-
打印: "
Please press Enter to activate this console. ";
-
等待回车
-
}
-
-
wpid = wait(NULL);
-
while (wpid > 0) {
-
a->pid = 0;
-
}
-
}
当然在busybox/example下,我们可以查到 inittab的格式说明:
-
# Format for each entry: <id>:<runlevels>:<action>:<process>
id --> /dev/it 用于终端:stdin, stdout,stderr
runlevels : 忽略
action :执行时机
process : 应用程序或脚本
这样第一个进程 init 就运行起来了。