Автозапуск программы как демона

Ответить
ya
^-^
Сообщения: 2336
Зарегистрирован: 16 дек 2021, 19:56

Автозапуск программы как демона

Сообщение ya »

Наверное ни для кого не секрет, что скрипты запускаемых служб в Linux
располагаются в /etc/rc.d/init.d или /etc/init.d в зависимости от
дистрибутива. Для того, чтобы скрипт запускался автоматически во время
запуска системы, надо создать символическую ссылку на скрипт и разместить
её в каталоге /etc/rc.d/rcN.d или /etc/rc.d/rcN.d, где N –
соответствует уровню выполнения скрипта.

Уровень 0
остановка системы (halt) - работа системы должна быть прекращена;

Уровень 1
однопользовательский режим работы - система инициализирует минимум
служб и даёт единственному пользователю (как правило,
суперпользователю) без проведения аутентификации командную строку.
Как правило, этот режим используется для восстановления системы;

Уровень 2
многопользовательский режим - пользователи могут работать на разных
терминалах, вход в систему с процессом аутентификации;

Уровень 3
многопользовательский сетевой режим - в отличие от предыдущего
уровня, осуществляется настройка сети и запускаются различные
сетевые службы;

Уровень 4
не имеет стандартного толкования и практически не используется;

Уровень 5
запуск графической подсистемы - по сравнению с уровнем 3
производится также старт графической подсистемы X11, и вход в
систему осуществляется уже в графическом режиме;

Уровень 6
перезагрузка системы - при включении этого режима останавливаются
все запущенные программы и производится перезагрузка.

Чаще всего во время загрузке система использует уровни загрузки 3 или 5.
Однако есть некоторая хитрость в названии самой символической ссылки, о
которой многие умалчивают, и о которой я хочу рассказать. Например:
/etc/rc.d/rc0.d/K60crond и /etc/rc.d/rc3.d/S40crond, указывающие на один
скрипт /etc/init.d/crond службы системного журнала. Скрипт, начинающийся
с "K" соответствует останову службы, а "S" - запуску. Числа, следующие
перед именем службы задают порядок запуска скриптов в директории.
Например, скрипт /etc/rc.d/rc3.d/S34syslogd будет запущен до скрипта
/etc/rc.d/rc3.d/S40crond, тогда как /etc/rc.d/rc3.d/K60crond до
/etc/rc.d/rc3.d/K66syslogd. Можно заметить, что сумма чисел для одной
службы равна 100 - это позволяет упорядочить все скрипты в порядке
старта, обратном порядку завершения. Создавать самому символические
ссылки весьма утомительно, и для этого лучше использовать специальную
утилиту chkconfig.


Синтаксис её использования весьма прост:

chkconfig --list [имя сервиса]
chkconfig --add <имя сервиса>
chkconfig --del <имя сервиса>
chkconfig [--level <уровни>] <имя сервиса> <on|off|reset|resetpriorities>


Где имя сервиса - это имя исполняемого скрипта находящегося в /etc/rc.d/init.d

Однако и тут есть небольшая хитрость, дело в том, что скрипт запуска
должен иметь специальный формат, например такой:

#!/bin/sh
# chkconfig: - 98 02
# description: Описание процесса
# processname: Имя процесса

# Source function library.
if [ -f /etc/init.d/functions ] ; then
. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
. /etc/rc.d/init.d/functions
else
exit 0
fi
KIND="Имя_сервиса"
start() {
echo -n $"Starting $KIND services: "
daemon /usr/local/sbin/исполняемый_файл
echo
}

stop() {
echo -n $"Shutting down $KIND services: "
killproc исполняемый_файл
echo
}

restart() {
echo -n $"Restarting $KIND services: "
killproc исполняемый_файл
daemon /usr/local/sbin/исполняемый_файл
echo
}

case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
*)
echo $"Usage: $0 {start|stop|restart}"
exit 1
esac
exit $?


Главное тут в следующем, во первых скрипт должен иметь как минимум 3
возможных ключа запуска, это: start, stop, restart, поскольку именно
эти основные команды используются для запуска, останова и перезапуска.
Плюс ко всему к этому в самом начале файла пишутся те самые заветные
цифры отвечающие за последовательность запуска:

# chkconfig: - 98 02


Где 98 это номер в последовательности запуска, а 02 это номер
последовательности останова.

То есть, проще говоря, этот скрипт запуститься 98мым в
последовательности очередей, а будет остановлен 2рым.

Теперь практикум.

Итак для того чтоб добавить скрипт и добавить его в автозагрузку надо
произвести следующую последовательность действий:

1. Создать исполняемый скрипт по шаблону приведёному выше, заменив
исполняемый_файл именем файла который надо запустить.

2. Разместить исполняемый скрипт в /etc/rc.d/init

3. Выполнить команду chkconfig --add исполняемый_скрипт

4. Выполнить команду setup или servicevonf (в зависимости от того
работаете вы в графическом режиме или консоли) и выбрать службу, которая
будет носить имя исполняемый_скрипт.
ya
^-^
Сообщения: 2336
Зарегистрирован: 16 дек 2021, 19:56

Re: Автозапуск программы как демона

Сообщение ya »

Run-time dependencies
Adding run-time dependencies was a release goal for Lenny, and dependency based boot sequencing is the default in Squeeze. There is a separate wiki page documenting that effort.

By documenting the run-time dependencies for init.d scripts, it becomes possible to verify the current boot order, order the boot using these dependencies, and run boot scripts in parallel to speed up the boot process.

Add a block like this in the init.d script:

### BEGIN INIT INFO
# Provides: scriptname
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable service provided by daemon.
### END INIT INFO
The block shown above has a special rigid format delimited by the lines


### BEGIN INIT INFO
### END INIT INFO
where all trailing spaces shall be ignored. On the other hand, all lines inside the block shall be of the form

# {keyword}: arg1 [arg2...]
and begin with a hash character '#' in the first column followed by one single space, except for the lines following the Description keyword. The following keywords are defined

Provides: boot_facility_1 [boot_facility_2...]

defines boot facilities provided by this init script such that when the script is run with the start argument, the specified boot facilities will be deemed present and hence other init scripts which require those boot facilities must be started at a later stage. Normally you should use the script name as boot facility (without .sh if the file name has such an ending) but one can in the exceptional case also use the name of the service(s) that the script replaces. Boot facilities provided by scripts must not start with '$'. (Virtual facility names listed below are defined outside the init.d scripts.) Facility names should be unique within the distribution, to avoid 'duplicate provides' errors when a package is installed.
Required-Start: boot_facility_1 [boot_facility_2...]

defines facilities that must be available to start the script. Consider using virtual facility names as described below if adequate. If no boot facility is specified it means that this script can be started just after the bootstrap without local filesystems mounted, nor system logger, etc.
Required-Stop: boot_facility_1 [boot_facility_2...]

defines facilities used by the service provided by the script. The facility provided by this script should stop before the listed facilities are stopped to avoid conflicts. Normally you would include here the same facilities as for the Required-Start keyword.
Should-Start: boot_facility_1 [boot_facility_2...]

defines the facilities that if present should start before the service provided by the script. Nevertheless, the script can still start if the listed facilities are missing. This allows for weak dependencies which do not cause the service to fail if a facility is not available. Consider using virtual facility names as described below if adequate.
Should-Stop: boot_facility_1 [boot_facility_2...]

defines the facilities that if present should be stopped after this service. Normally you would include here the same facilities as those used with the Should-Start keyword.
Default-Start: run_level_1 [run_level_2...]

Default-Stop: run_level_1 [run_level_2...]

defines the run levels where the script should be started (stopped) by default. For example, if a service should run in runlevels 3, 4, and 5 only, specify "Default-Start: 3 4 5" and "Default-Stop: 0 1 2 6".
Short-Description: short_description

provide a brief description of the actions of the init script. Limited to a single line of text.
Description: multiline_description

provide a more complete description of the actions of the init script. May span multiple lines. In a multiline description, each continuation line shall begin with a '#' followed by tab character or a '#' followed by at least two space characters. The multiline description is terminated by the first line that does not match this criteria.
X-Start-Before: boot_facility_1 [boot_facility_2...]

X-Stop-After: boot_facility_1 [boot_facility_2...]

provide reverse dependencies, that appear as if the listed facilities had should-start and should-stop on the package with these headers.
X-Interactive: true

Indicates that this init script can interact with the user, requesting some input (for example, a password). This make sure the script run alone when the boot system starts scripts in parallell and have direct access to the tty.
For dependency tracking, the provides, required- and should- keywords are important, and the rest is unused. The default runlevels are used by a program to order the init scripts (e.g. insserv) to keep track of which rc#.d directory to update when a service is added for the first time, and should reflect the intent of the service.

There are some "virtual" facility names, listed in the [LSB 3.1]. These are:

$local_fs

all local filesystems are mounted. All scripts that write in /var/ need to depend on this, unless they already depend on $remote_fs.

$network

low level networking (ethernet card; may imply PCMCIA running)

$named

daemons which may provide hostname resolution (if present) are running. For example, daemons to query DNS, NIS+, or LDAP.

$portmap

daemons providing ?SunRPC/ONCRPC portmapping service as defined in RFC 1833 (if present) are running all remote

$remote_fs

all filesystems are mounted. In some LSB run-time environments, filesystems such as /usr may be remote. If the script need a mounted /usr/, it needs to depend on $remote_fs. Scripts depending on $remote_fs do not need to depend on $local_fs. During shutdown, scripts that need to run before sendsigs kills all processes should depend on $remote_fs.

$syslog

system logger is operational

$time

the system time has been set, for example by using a network-based time program such as ntp or rdate, or via the hardware Real Time Clock. Note that just depending on ntp will not result in an accurate time just after ntp started. It usually takes minutes until ntp actually adjusts the time. Also note that standard insserv.conf just lists hwclock as $time.

$all

facility supported by insserv to start a script after all the scripts not depending on $all, at the end of the boot sequence. This only work for start ordering, not stop ordering. Depending on a script depending on $all will give incorrect ordering, as the script depending on $all will be started after the script depending on it.
ya
^-^
Сообщения: 2336
Зарегистрирован: 16 дек 2021, 19:56

Re: Автозапуск программы как демона

Сообщение ya »

Рассмотрим поближе файл skeleton. Первое с чего он должен начинаться, конечно же "#!/bin/sh", т.к. init-скрипт — запускной файл. Далее идёт комментированный заголовок:
### BEGIN INIT INFO
# Provides: skeleton
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Example initscript
# Description: This file should be used to construct scripts to be
# placed in /etc/init.d.
### END INIT INFO

Может показаться, что это просто лишняя информация от автора, но это не так. То, что указано здесь используется при прописывании скрипта в систему. Тут как раз пригодится файл README, который показывает, что в заголовке skeleton перечислены не все возможные параметры. Как минимум есть ещё следующие:
# Should-Start: $portmap
# Should-Stop: $portmap
# X-Start-Before: nis
# X-Stop-After: nis
# X-Interactive: true
Ответить