- Init process on UNIX and Linux systems
- Runlevels
- Booting
- Changing Runlevels
- TELINIT
- init command in Linux with examples
- Standard Run Levels for Red Hat Based Distribution:
- linux-notes.org
- Пишем Init скрипт
- Пишем Upstart скрипт
- Примеры Init скрипта
- 4 thoughts on “ Пишем Init скрипт ”
- Команда init в Linux с примерами
- Стандартные уровни выполнения для распространения на основе Red Hat:
- Init calls in linux
- Purpose and usage
- Examples
- module_init()
- Debugging
- Implementation
- Conclusion
Init process on UNIX and Linux systems
Init is the parent of all processes, executed by the kernel during the booting of a system. Its principle role is to create processes from a script stored in the file /etc/inittab. It usually has entries which cause init to spawn gettys on each line that users can log in. It controls autonomous processes required by any particular system.
After reading this file, how the system should be set up in each runlevel is determined by init and also set default runlevel. Init starts all background process after setting default runlevel for the system.
Runlevels
Runlevel, a software configuration of the system which allows only a selected group of processes to exist. The processes produced by init for each of these runlevels are defined in the /etc/inittab file.
Init can be in one of these eight runlevels: 0-6 and S or s. The runlevel can be changed by having a privileged user run telinit, which sends appropriate signals to init, telling it which runlevel to change to.
S or s are same.
7-9 are valid runlevels. though not really documented as «traditional» Unix variants don’t use them. runlevels S and s are in fact the same. Internally they are aliases for the same runlevel.
Runlevels | Functions |
---|---|
0 | To halt the system |
1 | To get the system down into single user mode |
2 | To get multiuser mode without networking |
3 | To get multiuser mode with networking |
4 | Not used |
5 | To get multiuser mode with networking and X windows |
6 | To reboot the system |
S or s | Not used directly. |
Booting
After invoking init as the last step of the kernel boot sequence, it sees if an entry of the type initdefault is present in the file /etc/inittab. The initdefault entry determines the initial runlevel of the system. If no such entry (or no /etc/inittab at all) is present there, a runlevel must be entered at the system console.
Changing Runlevels
After specifying all the processes, init waits for one of its descendant processes to die, a powerfail signal, or until it is signaled by telinit to change the system’s runlevel. It re-examines the /etc/inittab file, when one of the above three conditions occurs.
init still waits for one of the above three conditions to occur. For providing an instantaneous response, the telinit Q or q command can wake up init to re-examine the/etc/inittab file.
If init is not in single user mode and receives a powerfail signal (SIGPWR), it reads the file /etc/powerstatus. Then it starts a command based on the contents of this file −
Tag | Description |
---|---|
F(AIL) | Power is failing, UPS is providing the power. Execute the powerwait and powerfail entries. |
O(K) | Power has been restored, execute the powerokwait entries. |
L(OW) | The power is failing and the UPS has a low battery. Execute the powerfailnow entries. |
If /etc/powerstatus contains anything else then the letters F, O or L or doesn’t exist, init will behave as if it has read the letter F.
Usage of SIGPWR and /etc/powerstatus is discouraged. If Someone wanting to interact with init should use the /dev/initctl control channel — see the source code of the sysvinit package for more documentation about this.
When init is requested to change the runlevel, it sends the warning signal SIGTERM to all processes that are undefined in the new runlevel. Then It waits 5 seconds before forcibly terminating these processes via the SIGKILL signal.
Init assumes that all these processes and their descendants remain in the same process group which init originally created for them. It will not receive these signals, if any process changes its process group affiliation. Such processes need to be terminated separately.
TELINIT
/sbin/telinit is linked to /sbin/init which takes a one-character argument and signals init to perform the appropriate action. The following arguments serve as directives to telinit −
Tag | Description |
---|---|
0,1,2,3,4,5 or 6 | tell init to switch to the specified run level. |
a, b, c | tell init to process only those /etc/inittab file entries having runlevel a, b or c. |
Q or q | tell init to re-examine the /etc/inittab file. |
S or s | tell init to switch to single user mode. |
U or u | tell init to re-execute itself (preserving the state). No re-examining of/etc/inittab file happens. Request would be silently ignored, if Run level is not one of Ss12345. |
It can also tell init how long it should wait between sending processes the SIGTERM and SIGKILL signals. 5 seconds is the default, but this can be changed with the -t sec option.
Only by users with appropriate privileges can invoke telinit.
By looking at its process id, init binary checks if it is init or telinit; the real init’s process id is always 1. So, instead of calling telinit one can also just use init instead as a shortcut.
Источник
init command in Linux with examples
init is parent of all Linux processes with PID or process ID of 1. It is the first process to start when a computer boots up and runs until the system shuts down. init stands for initialization. In simple words the role of init is to create processes from script stored in the file /etc/inittab which is a configuration file which is to be used by initialization system. It is the last step of the kernel boot sequence.
- init script initializes the service. So, it responsible for initializing the system.
- Init scripts are also called rc scripts (run command scripts)
- Init script is also used in UNIX.
Syntax
Run Levels is the state of init where a group of processes are defined to start at the startup of OS. The process spawned by init for each of this run levels are defined in the file /etc/inittab. Each runlevel has a certain number of services stopped or started. Conventionally seven runlevel exist numbers from zero to six.
Standard Run Levels for Red Hat Based Distribution:
Runlevel
Does not configure network interfaces, start daemons,
or allow non-root logins
By default most of the LINUX based system boots to runlevel 3 or runlevel 5. In addition to the standard runlevels, users can modify the preset runlevels or even create new ones according to the requirement. Runlevels 2 and 4 are used for user defined runlevels and runlevel 0 and 6 are used for halting and rebooting the system.
Источник
linux-notes.org
Пишем Init скрипт
Инициализация — важнейшая процедура, лежащая в основе любой операционной системы на основе Unix/Linux для управления работой каждого скрипта и службы.
Я описывал в своих статьях процесс создания скриптов для systemD/Upstart и сейчас я хотел бы написать о написании init скриптов. Тема не новая и используется давно, но я большую часть своих тем беру именно из черновиков, которые накопились за года 3-4. У меня не хватает времени на все публикации + наполнять контент максимально (по крайней мере, сразу) и по этому, имеет что имеем. Но не смотря на это, у меня уже довольно много читателей — и это хорошо, это радует!
По сути, инициализация следует за этим процессом:
- Загрузка сервера.
- Запуск init процесса (обычно как PID 1).
- Запуск предопределенного набора задач для запуска активируется последовательно.
Инициализация отвечает за то, чтобы сервер мог загрузиться и отключиться. В некоторых Unix/Linux дистрибутивах используется стандартный процесс инициализации init/systemD/Upstart.
Пишем Upstart скрипт
И так, хотелось бы рассказать как можно запускать томкат. Но для начала, нужно узнать какой механизм инициализации используется:
Т.к речь идет о sysv init/Upstart, то и продолжим тему.
PS: Вот еще полезное чтиво:
INIT скрипт может иметь следующие состояния:
- start — Служит командой для запуска службы.
- stop — Выполняет остановку службы.
- restart — Перезапуст службы, а по факту — остановка и затем запуск сервиса.
- reload — Перезагрузка службы, т.е команда для перечитывания конфигурации без перезапуска или остановки службы.
- force-reload — Перезагрузка конфигурации (перечитать конфиг), если служба поддерживает это. В противном случае — выполнит перезапуск службы.
- status — Покажет состояние службы.
Вот скилет скрипта для использования:
Данный каркас можно юзать для любых целей.
Примеры Init скрипта
Приведу наглядный пример запуска томката.
Запуск TOMCAT с init
Создадим init скрипт для запуска:
И приводим к виду:
Даем права на запуск (на исполнение):
Открываем браузер и смотрим что вышло!
Вот еще один скрипт:
Подойдет к большинству скриптов, а для остальных — можно отредактировать немного.
И, вот еще полезный довольно вариант:
Вот и все, статья «Пишем Init скрипт» завершена.
4 thoughts on “ Пишем Init скрипт ”
Неверно указана ссылка «Система инициализации SysVinit», исправьте.
Источник
Команда init в Linux с примерами
Главное меню » Linux » Команда init в Linux с примерами
- Сценарий инициализации инициализирует службу. Итак, он отвечает за инициализацию системы.
- Сценарии инициализации также называются сценариями rc (сценарии запуска команд)
- Сценарий инициализации также используется в UNIX.
Уровни выполнения – это состояние init, в котором определена группа процессов, запускаемых при запуске ОС. Процесс, порожденный init для каждого из этих уровней запуска, определяется в файле /etc/inittab. На каждом уровне выполнения определенное количество остановленных или запущенных служб. Условно семь уровней выполнения существуют числами от нуля до шести.
Стандартные уровни выполнения для распространения на основе Red Hat:
или разрешить вход без полномочий root
По умолчанию большая часть системы на основе LINUX загружается на уровень выполнения 3 или уровень выполнения 5. В дополнение к стандартным уровням выполнения пользователи могут изменять предустановленные уровни выполнения или даже создавать новые в соответствии с требованиями. Уровни выполнения 2 и 4 используются для определенных пользователем уровней выполнения, а уровни выполнения 0 и 6 используются для остановки и перезагрузки системы.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
Init calls in linux
Share this post:
Initcalls, which serve to call functions during boot, were implemented early on in the development of the Linux Kernel. While they have not required significant changes since version 2.4 released around 2001, tracing support was added by Steven Rostedt in 2018, which can be useful to measure time spent on each initcall to allow for further debugging.
Read on as we take a closer look at initcalls, including their purpose in the Linux kernel, their usage (how to create your function and call one of the definitions), ways to debug them (using initcall_debug or FTrace), as well as a short overview of their implementation.
Purpose and usage
As mentioned, the purpose of initcalls are to call functions at different stages during the boot process and are used in many architectures and drivers:
Initcalls are defined as regular functions with the __init attribute and one of the helpers which will define the type of initcall you want to use. Here is a list of initcalls and their distributions in the code:
The implementation will be explained in the next part of this blog post but keep in mind the main ideas behind initcalls:
- Using initcalls will create ELF sections in the object file.
- The programmer creates the needed function that will go into these specific sections.
- Those sections will be iterated later by the kernel which will execute functions located there.
- Each section corresponds to one initcall level.
If you are not familiar with the ELF (Extensible Linking Format) file format, see this a very nice overview by Corkami:
Examples
Here is an example of an initcall which will be executed at the postcore stage.
You will find many real-world examples in the kernel. For instance, the proc filesystem entry creation for all kernel debug symbols:
Using initcalls implies some benefits: your code is more modular and maintainable because we don’t need to explicitly pass, store and call function pointers — instead we only mark function as appropriate level initcall and it will be automagically invoked at the appropriate time. However, knowing which one should be used is difficult to distinguish. The level name reflects the order of initcall, in which part initcall will be called, but you have to understand the dependencies and where your function should be executed.
Sometimes, using an initcall is not necessary and using module_init() can be enough. Notices that these initcalls function can be used only for builtin modules. For modules that can also be loadable, module_init() is the key.
module_init()
Initcalls are executed at early stages of the initialization of a module but only for the ones that are statically linked to the kernel. But how about modules than can be loadable or builtin? Many modules (builtin or loadable) don’t need to be executed so early because they are not necessary for a device to become usable, for example. In that case, you should use one of the last initcalls levels or module_init() . Thanks to that, it will save time consumed at bootup and let most important probing functions to be executed earlier.
If a module is compiled builtin ( y in your configuration), module_init() function will be called during do_initcalls() because this function will be a simple link to device_initcall function (i.e one of the last initcalls during boot process). Here is the code in include/linux/module.h :
And __initcall() is calling device_initcall() :
In case of a loadable module, it will be during the insertion time by using syscalls. All initcalls function will be replaced by a module_init() one:
We will see this use case in the second article that will go deeper in the module_init() implementation.
To summarize, if you don’t have any reasons to execute a function at early stage in booting process, you should use module_init() if your module can be loaded (which is the case in most of non-core drivers).
Debugging
A debug command-line parameter exists to print 2 messages while executing all initcalls functions. For that, you should use initcall_debug introduced in 2.5.67 in the command-line.
This is a great debug parameters to detect which initcalls are taking too much time, particularly in case of boot-time improvements. However, as these debug logs are directly printed on the console and it is printing messages for all initcalls, it can be difficult to retrieve a particular information in this verbose log without having our great binary: grep .
This is why ftrace has been introducted on initcalls. If you are not familiar with FTrace, here is a really nice video from Steven Rostedt.
Here is a little example of how to use it in case of initcalls-tracing:
- The available events can be retrieved using the debugfs entry:
- If you are familiar with FTracing, using it for initcalls is a little different because we need to configure it before the boot process. That’s why we have to add parameters to the command-line to configure which events we want to retrieve. Example of my command-line to retrieve all initcall_level , initcall_start and initcall_finish events :
- And you can retrieve the current event through trace entry on debugfs:
Once again, FTrace logging allows to have great information to detect portions of code whose execution take a lot of time.
Implementation
Now we know what initcalls are for, let’s look at how they are implemented in Linux Kernel’s code. One part of the implementation of initcalls is in include/linux/init.h .
Initcalls are defined thanks to a generic __define_initcall() with two arguments:
- The function name
- An id which is a way to order the initcalls. The ordering is not according to a number because if you look closer at this argument, its value is equals to rootfs for rootfs_initcall() . All initcalls defined using postcore_initcall will have a second argument of 2. This is the main difference between all initcalls: the ID (that can be both number and string, see rootfs ). It will be different depending on the type of initcall used.
Note: Let’s focus on postcore_initcall in the rest of this article.
Let’s look at this definition in the kernel source:
You have our dummy example: a simple function that is defined as a postcore initcall. The postcore_initcall definition is calling the __define_initcall() with its ID: 2. The __define_initcall(fn, id) is calling another define_initcall() with an additional arguments: __sec . For all initcalls, it will be equals to .initcall + the id of the initcall. For our postcore initcall, the last parameter will be .initcall2 .
The last __define_initcall() will look like this (code and expanded versions):
Too many colors, right?
Let’s take a break for now and keep the explanation of that part for the next article!
Conclusion
In this first blog post, we have seen an overview of initcalls:
- their purpose: being able to call a function at different stages of the kernel booting process;
- their usage: simply create your function and call one of the definitions of initcalls depending on the level of the booting process you need ( core_initcall , postcore_initcall , fs_initcall , device_initcall , . );
- a short explanation of module_init() function and the difference (or not. ) with initcalls;
- 2 ways to debug initcalls: initcall_debug and FTrace. They are very useful in case the boot-time must be as fast as possible;
- and a short overview of their implementation in the kernel: each initcall has an id corresponding to its level and their implementation is based on __define_initcall() .
The next part will go deeper into the implementation of initcalls, particularly about this colorful __device_initcall() macro.
Источник