- The Linux Booting Process — 6 Steps Described in Detail
- 1. BIOS
- 2. MBR
- 3. GRUB
- 4. Kernel
- 5. Init
- 6. Runlevel programs
- 6 шагов загрузки Linux на пальцах
- 1. BIOS
- 2. MBR
- 3. GRUB
- 4. Ядро или Kernel
- 5. Init
- 6. Уровень выполнения программ (Runlevel)
- Дополнения, исправления, уточнения
- Linux Boot Process Explained Step by Step in Detail
- Stages of Linux Boot Process (flowchart)
- 1. BIOS Stage
- 2. Boot Loader Stage
- 3. Kernel Stage
- Related Posts
- 6 thoughts on “Linux Boot Process Explained Step by Step in Detail”
The Linux Booting Process — 6 Steps Described in Detail
An operating system (OS) is the low-level software that manages resources, controls peripherals, and provides basic services to other software. In Linux, there are 6 distinct stages in the typical booting process.
1. BIOS
BIOS stands for Basic Input/Output System. In simple terms, the BIOS loads and executes the Master Boot Record (MBR) boot loader.
When you first turn on your computer, the BIOS first performs some integrity checks of the HDD or SSD.
Then, the BIOS searches for, loads, and executes the boot loader program, which can be found in the Master Boot Record (MBR). The MBR is sometimes on a USB stick or CD-ROM such as with a live installation of Linux.
Once the boot loader program is detected, it’s then loaded into memory and the BIOS gives control of the system to it.
2. MBR
MBR stands for Master Boot Record, and is responsible for loading and executing the GRUB boot loader.
The MBR is located in the 1st sector of the bootable disk, which is typically /dev/hda , or /dev/sda , depending on your hardware. The MBR also contains information about GRUB, or LILO in very old systems.
3. GRUB
Sometimes called GNU GRUB, which is short for GNU GRand Unified Bootloader, is the typical boot loader for most modern Linux systems.
The GRUB splash screen is often the first thing you see when you boot your computer. It has a simple menu where you can select some options. If you have multiple kernel images installed, you can use your keyboard to select the one you want your system to boot with. By default, the latest kernel image is selected.
The splash screen will wait a few seconds for you to select and option. If you don’t, it will load the default kernel image.
In many systems you can find the GRUB configuration file at /boot/grub/grub.conf or /etc/grub.conf . Here’s an example of a simple grub.conf file:
4. Kernel
The kernel is often referred to as the core of any operating system, Linux included. It has complete control over everything in your system.
In this stage of the boot process, the kernel that was selected by GRUB first mounts the root file system that’s specified in the grub.conf file. Then it executes the /sbin/init program, which is always the first program to be executed. You can confirm this with its process id (PID), which should always be 1.
The kernel then establishes a temporary root file system using Initial RAM Disk (initrd) until the real file system is mounted.
5. Init
At this point, your system executes runlevel programs. At one point it would look for an init file, usually found at /etc/inittab to decide the Linux run level.
Modern Linux systems use systemd to choose a run level instead. According to TecMint, these are the available run levels:
Run level 0 is matched by poweroff.target (and runlevel0.target is a symbolic link to poweroff.target).
Run level 1 is matched by rescue.target (and runlevel1.target is a symbolic link to rescue.target).
Run level 3 is emulated by multi-user.target (and runlevel3.target is a symbolic link to multi-user.target).
Run level 5 is emulated by graphical.target (and runlevel5.target is a symbolic link to graphical.target).
Run level 6 is emulated by reboot.target (and runlevel6.target is a symbolic link to reboot.target).
Emergency is matched by emergency.target.
systemd will then begin executing runlevel programs.
6. Runlevel programs
Depending on which Linux distribution you have installed, you may be able to see different services getting started. For example, you might catch starting sendmail …. OK .
These are known as runlevel programs, and are executed from different directories depending on your run level. Each of the 6 runlevels described above has its own directory:
- Run level 0 – /etc/rc0.d/
- Run level 1 – /etc/rc1.d/
- Run level 2 – /etc/rc2.d/
- Run level 3 – /etc/rc3.d/
- Run level 4 – /etc/rc4.d/
- Run level 5 – /etc/rc5.d/
- Run level 6 – /etc/rc6.d/
Note that the exact location of these directories varies from distribution to distribution.
If you look in the different run level directories, you’ll find programs that start with either an «S» or «K» for startup and kill, respectively. Startup programs are executed during system startup, and kill programs during shutdown.
That’s everything you need to know about the Linux booting process. Now go out there and make Tux proud.
If this article was helpful, tweet it.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.
Источник
6 шагов загрузки Linux на пальцах
Нажмите кнопку включения питания на вашем системнике, и спустя несколько секунд вы увидите окно входа в систему.
Посмею предположить, что каждого интересовало хоть когда-либо то, что происходит за занавесом заставок и загрузочных экранов с момента включения питания компьютера к моменту, когда предлагается войти в систему.
Я предлагаю вам познакомиться со следующими уровнями типичной загрузки Linux:
1. BIOS
2. MBR
3. GRUB
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.18-194.el5PAE)
root (hd0,0)
kernel /boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/
initrd /boot/initrd-2.6.18-194.el5PAE.img
4. Ядро или Kernel
5. Init
6. Уровень выполнения программ (Runlevel)
- Когда Линукс выполняет свою загрузку, вы можете наблюдать загрузку различных служб. К примеру, это могут быть сообщения типа «starting Postfix … OK» (запускается Postfix). Эти службы — и называются программами уровня выполнения, выполняемые из директории, которая соответствует нужному уровню выполнения.
- Исходя из настроек по умолчанию, система будет выполнять файлы в соответствии с нижеприведенными директориями.
- Выполнение уровня 0 – /etc/rc.d/rc0.d/
- Выполнение уровня 1 – /etc/rc.d/rc1.d/
- Выполнение уровня 2 – /etc/rc.d/rc2.d/
- Выполнение уровня 3 – /etc/rc.d/rc3.d/
- Выполнение уровня 4 – /etc/rc.d/rc4.d/
- Выполнение уровня 5 – /etc/rc.d/rc5.d/
- Выполнение уровня 6 – /etc/rc.d/rc6.d/
- Но имейте ввиду, что еще в каталоге /etc могут быть символические ссылки. Например, /etc/rc0.d залинкован на /etc/rc.d/rc0.d.
- В каталогах /etc/rc.d/rc*.d/ вы можете увидеть список программ, имя которых начинается из букв S и K.
- Программы, начинающиеся на S используются для запуска. S, потому что startup.
- Программы, которые начинаются с литеры K используются — правильно — для завершения работы. K, потому что kill.
- Еще есть номера рядом с буквами S и K в именах программ. Эти номера используются для определения порядка запуска этих программ.
- К примеру, S12syslog предназначен для запуска демона syslog, его порядковый номер 12. S80sendmail — для запуска демона sendmail, имеющего порядковый номер 80. Таким образом, программа syslog будет запущена перед sendmail.
Вот и все. Возможно, некоторым из вас это не ново и особого интереса не было при чтении статью, поскольку она более ориентирована на начально-средний уровень знакомства з Линуксом.
В таком случае могу лишь сказать, что «повторение — мать учения» (с).
Дополнения, исправления, уточнения
В комментариях неоднократно было апеллировано к тексту статьи, поэтому, думаю, стоит учесть некоторые важные комментарии хабрасообщества. (спасибо artemlight, 3al, Tishka17, HhyperH, Next_Alex, Ilya_Shmelykh, Aux, soomrack, Xpeh )
- artemlight:: «Ну скажем прямо — так грузятся далеко не все дистры». С ним согласилось большинство, отмечая и bsd-style init, u-boot, и хоть initrd в статье пропущен, стоить заметить, что он нужен ядру не во всех дистрибутивах. Также отмечено, что в slackware поддержка rc.d осуществляется только в качестве совместимости, а встраиваемые системы грузятся иначе. На декстопах иногда бывает EFI, а кроме того Linux популярен в мире embedded и там ещё куча разных платформ. Линукс в телефоне вообще иначе грузится.
- soomrack, ссылая на википедию: Еще хочется сделать замечание по поводу MBR, первого сектора и пр. Все несколько усложнилось за последние годы. Сейчас уместней говорить о EFI.
Источник
Linux Boot Process Explained Step by Step in Detail
Table of Contents
In this article I will give you an step by step overview of Linux boot process with some flowchart diagrams which can help you understand better.
Stages of Linux Boot Process (flowchart)
- BIOS Stage
- Boot Loader Stage
- Kernel Stage
1. BIOS Stage
- When the machine is powered on BIOS is the first one to be called to verify if the hardware is present in the machine and if it is functioning.
- This is done by performing a Power On Self Test (POST)
- After a successful test, BIOS checks the MBR (Master Boot Record) in the hard disk to check if it refers to the location of the boot loader.
2. Boot Loader Stage
The boot loader will be installed if an operating system is installed on the system.
Two of the most common boot loaders are
- The boot loader will present the user with a list of menu entries, each of which corresponds to different operating system
- The boot loader will then start to boot the operating system
- When you select the the option to start Linux, it decompresses the Linux kernel in memory
- After that Linux kernel (which you selected to boot from) loads initrd (Initial ramdisk)
- The initrd is used by the Linux kernel as a temporary filesystem in the memory
- It contains tools and kernel modules which will continue the boot process including mounting a virtual root file system temporarily.
- Instead of using initrd, some Linux filesystem will also use initramfs.
- It serves the same purpose of initrd, it is just that it is a successor of initrd
- linuxrc is an executable file that is next spawn, it probes the mass storage hardware and finds a suitable kernel module to drive the mass storage hardware
- This is required to prepare the real root filesystem to be mounted by the Linux kernel
3. Kernel Stage
- In the kernel stage of the Linux boot sequence, the Linux kernel based on the result of linuxrc can then mount the real root file system
- The real root file system in Linux is referenced as «/» and it is where all other sub directory and files visible when Linux is running exist
- The kernel will then spawn the init process, this process always has the process identifier (PID) as «1» because it is the first background process or daemon started by the kernel upon boot
- All other background daemons are spawned from the init process
- So the init process will load other system daemons depending upon the configuration of different runlevel
For example:
- If the system boots into runlevel 3 then the init process will start all the daemons from this runlevel.
Lastly I hope the Linux Boot process explained using flowchart in this article was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
6 thoughts on “Linux Boot Process Explained Step by Step in Detail”
This is the best explanation I’ve ever seen in the Internet for the Linux boot process.
Hi there, I read your new stuff like every week.
Your story-telling style is awesome, keep doing what you’re doing!
Is the arrow from bootloader to initrd correct? You say “After that Linux kernel creates initrd”
So the arrow should go from kernel to initrd, shouldn’t it?
Thank you for highlighting, the text can be little confusing here so I reworded it. The flow chart is correct. The Linux kernel doesnot creates initrd, instead initrd is part of kernel whichcontains important binaries to load virtual file system and detect the hardware to proceed with the boot up.
Источник