Linux services and demons

Services and Daemons — runit

Void uses the runit(8) supervision suite to run system services and daemons.

Some advantages of using runit include:

  • a small code base, making it easier to audit for bugs and security issues.
  • each service is given a clean process state, regardless of how the service was started or restarted: it will be started with the same environment, resource limits, open file descriptors, and controlling terminals.
  • a reliable logging facility for services, where the log service stays up as long as the relevant service is running and possibly writing to the log.

If you don’t need a program to be running constantly, but would like it to run at regular intervals, you might like to consider using a cron daemon.

Section Contents

Service Directories

Each service managed by runit has an associated service directory.

A service directory requires only one file: an executable named run , which is expected to exec a process in the foreground.

Optionally, a service directory may contain:

  • an executable named check , which will be run to check whether the service is up and available; it’s considered available if check exits with 0.
  • an executable named finish , which will be run on shutdown/process stop.
  • a conf file; this can contain environment variables to be sourced and referenced in run .
  • a directory named log ; a pipe will be opened from the output of the run process in the service directory to the input of the run process in the log directory.

When a new service is created, a supervise folder will be automatically created on the first run.

Configuring Services

Most services can take configuration options set by a conf file in the service directory. This allows service customization without modifying the service directory provided by the relevant package.

Читайте также:  Linux list folders with sizes

Check the service file for how to pass configuration parameters. A few services have a field like OPTS=»—value . » in their conf file.

To make more complex customizations, you should edit the service.

Editing Services

To edit a service, first copy its service directory to a different directory name. Otherwise, xbps-install(1) can overwrite the service directory. Then, edit the new service file as needed. Finally, the old service should be stopped and disabled, and the new one should be started.

Managing Services

Runsvdirs

A runsvdir is a directory in /etc/runit/runsvdir containing enabled services in the form of symlinks to service directories. On a running system, the current runsvdir is accessible via the /var/service symlink.

The runit-void package comes with two runsvdirs, single and default :

  • single just runs sulogin(8) and the necessary steps to rescue your system.
  • default is the default runsvdir on a running system, unless specified otherwise by the kernel command line.

Additional runsvdirs can be created in /etc/runit/runsvdir/ .

See runsvdir(8) and runsvchdir(8) for further information.

Booting A Different runsvdir

To boot a runsvdir other than default , the name of the desired runsvdir can be added to the kernel command-line. As an example, adding single to the kernel command line will boot the single runsvdir.

Basic Usage

To start, stop, restart or get the status of a service:

# sv up # sv down # sv restart # sv status
  • Service names (service directory names) inside the /var/service/ directory.
  • The full paths to the services.

For example, the following commands show the status of a specific service and of all enabled services:

# sv status dhcpcd # sv status /var/service/* 

See sv(8) for further information.

Enabling Services

Void Linux provides service directories for most daemons in /etc/sv/ .

To enable a service on a booted system, create a symlink to the service directory in /var/service/ :

If the system is not currently running, the service can be linked directly into the default runsvdir:

# ln -s /etc/sv/ /etc/runit/runsvdir/default/ 

This will automatically start the service. Once a service is linked it will always start on boot and restart if it stops, unless administratively downed.

Читайте также:  Linux устройства ввода вывода

To prevent a service from starting at boot while allowing runit to manage it, create a file named down in its service directory:

The down file mechanism also makes it possible to disable services that are enabled by default, such as the agetty(8) services for ttys 1 to 6. This way, package updates which affect these services (in this case, the runit-void package) won’t re-enable them.

Disabling Services

To disable a service, remove the symlink from the running runsvdir:

Or, for example, from the default runsvdir, if either the specific runsvdir, or the system, is not currently running:

# rm /etc/runit/runsvdir/default/

Testing Services

To check if a service is working correctly when started by the service supervisor, run it once before fully enabling it:

# touch /etc/sv//down # ln -s /etc/sv/ /var/service/ # sv once

If everything works, remove the down file to enable the service.

Источник

Службы и демоны в Linux, системы инициализации

Отличительной чертой, выделяющей демоны среди других процессов, является отсутствие их связи с терминалом.

Вывод демонизованного процесса может писаться в лог или подавляться (подавление вывода реализуется его перенаправлением в /dev/null)

Примером демона может быть apache2 и любые другие утилиты, запускающиеся при помощи инициализационных скриптов вместе с системой и работающие постоянно «в фоновом режиме».

Типовой задачей системного администрирования является написание собственных демонов.

Демоны Linux и управление ими

Демоны обычно имеют конфигурационные файлы и выделяются тем. что могут запускаться и останавливаться пользователем вручную командами вида: service deamonname start / service deamonname stop / service deamonname restart

Чтобы найти конфигурационные файлы пакета можно использовать whereis:

Вывод команды примерно следующий:

apache2: /usr/sbin/apache2 /usr/lib/apache2 /etc/apache2 /usr/share/apache2 /usr/share/man/man8/apache2.8.gz

Также информацию о конфигурационных файлах часто можно найти в man программного пакета

В случае с самым распространенным веб-сервером — конфигурационные файлы находятся в /etc/apache2

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

В конфигурационных файлах задается логирование — в случае если пакет работает неправильно — включить логирование или изменить его параметры.

Читайте также:  Delete directory in linux terminal

Часто демоны работают от имени системных пользователей, специально для них создаваемых — так apache может работать от имени пользователя www-data или от имени пользователя apache.

Демоны Linux стартуют вместе с системой, родительским процессом для них является init

Запуск демона с использованием init синтаксиса:

Инициализационные скрипты демонов, управляемых init, можно посмотреть в каталоге /etc/init.d/

В инициализационных скриптах указываются, в частности, runlevel-ы на которых демон стартует и останавливается.

Runlevels в Linux

0 Выключенное состояние (ядро не функционирует)
1 Режим использования одним пользователем (ядро функционирует, возможна авторизация, никакие сервисы не работают)
2 Режим, позволяющий работать нескольким пользователем и сети
3 Мультипользовательский режим с сетью
5 Мультипользовательский режим с сетью и GUI
6 Перезагрузка

В современном Linux init используется все реже поскольку данная система является устаревшей — она была создана довольно давно и плохо работает при необходимости обрабатывать данные поступающие в несколько потоков.

Замещается init системами upstart и systemd

upstart замещает все инициализационные скрипты конфигурационными файлами, они находятся в /etc/init

Управляются демоны, использующие upstart, следующим образом:

В 2014 году начался переход от upstart к systemd. Многие дистрибутивы сейчас используют одновременно несколько систем инициализации.

Среди использующих systemd — Fedora:

Также используя systemd можно легко добавлять демоны в автозагрузку (демон будет стартовать при старте системы)

В init и upstart для того чтобы включить/выключить автозагрузку достаточно добавить/удалить инициализационный файл или скрипт из каталога /etc/init в init и /etc/init.d в upstart (или воспользоваться скриптом update-rc.d — update-rc.d defaults apache2 чтобы добавить сервис в автозагрузку и update-rc.d remove apache2 чтобы его удалить из автозагрузки).

Часто применяется также runit — удобная система, которая также позволяет управлять сервисами (sv s apache2 / sv t apache2 / sv d apache2).

На одной машине могут использоваться демоны, управляемые при помощи различных систем инициализации. Так на сервере часть ПО может запускаться посредством init скриптов, часть — под runit.

Читайте про то, как добавить собственный скрипт, который будет выполняться после старта системы. Часто это бывает нужно чтобы добавить дополнительный функционал и свои скрипты.

Источник

Оцените статью
Adblock
detector