From 0b1812d2359c386253a53b8b8d090d15c4a7e435 Mon Sep 17 00:00:00 2001 From: Morgan Date: Sun, 26 Nov 2023 07:48:51 +0000 Subject: [PATCH] =?UTF-8?q?Create=20Post=20=E2=80=9C2023-11-26-kernel-crea?= =?UTF-8?q?tion-of-new-process=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...23-11-26-kernel-creation-of-new-process.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 content/posts/2023-11-26-kernel-creation-of-new-process.md diff --git a/content/posts/2023-11-26-kernel-creation-of-new-process.md b/content/posts/2023-11-26-kernel-creation-of-new-process.md new file mode 100644 index 0000000..83f3fc6 --- /dev/null +++ b/content/posts/2023-11-26-kernel-creation-of-new-process.md @@ -0,0 +1,46 @@ +--- +title: Kernel, creation of new process +date: 2023-11-26T07:44:51.449Z +slug: kernel-new-process-creation +description: "Deep dive Linux Kernel #3" +--- +```c +static int init(void * unused) +{ + lock_kernel(); + do_basic_setup(); + + /* + * Ok, we have completed the initial bootup, and + * we're essentially up and running. Get rid of the + * initmem segments and start the user-mode stuff.. + */ + free_initmem(); + unlock_kernel(); + + if (open("/dev/console", O_RDWR, 0) < 0) + printk("Warning: unable to open an initial console.\n"); + + (void) dup(0); + (void) dup(0); + + /* + * We try each of these until one succeeds. + * + * The Bourne shell can be used instead of init if we are + * trying to recover a really broken machine. + */ + + if (execute_command) + execve(execute_command,argv_init,envp_init); + execve("/sbin/init",argv_init,envp_init); + execve("/etc/init",argv_init,envp_init); + execve("/bin/init",argv_init,envp_init); + execve("/bin/sh",argv_init,envp_init); + panic("No init found. Try passing init= option to kernel."); +} +``` + +At `open("/dev/console") is opens fd 0, and with two `dup(0)`, fd 0, 1, 2 as stdin, stdout, stderr opens. When `execve()` or `fork()` happens, it simply copies calling process's `task_struct` as process context, so all file descriptors are also passed down. + +All processes' file descriptor 0, 1, 2 are all originates to `init`'s file descriptor, set up like above.