Start and stop daemons on linux

START-STOP-DAEMON

provides a consistent method of starting, stopping and signaling daemons. If neither —K , -stop nor —s , -signal are provided, then we assume we are starting the daemon. If a daemon cannot background by itself, nor create a pidfile, can do it for the daemon in a secure fashion.

If is used in an OpenRC service, then OpenRC can in turn check to see if the daemon is still running. If not, then the service is marked as crashed.

Here are the options to specify the daemon and how it should start or stop:

-x , -exec daemon The daemon we start or stop. If this option is not specified, then the first non option argument is used. -p , -pidfile pidfile When starting, we expect the daemon to create a valid pidfile within a reasonable amount of time. When stopping we only stop the first pid listed in the pidfile -n , -name name Match the process name instead of a pidfile or executable. -i , -interpreted When matching process name, we should ensure that the correct interpreter is also matched. So if the daemon foo starts off like so then matches the process If an interpreted daemon changes its process name then this won’t work. -u , -user user [: group ] Start the daemon as the user and update $HOME accordingly or stop daemons owned by the user. You can optionally append a group name here also. -t , -test Print the action(s) that would be taken, but don’t actually do anything. The return value is set as if the command was taken and worked. -v , -verbose Print the action(s) that are taken just before doing them. -P , -progress Echo a . to the console for each second elapsed whilst waiting.

These options are only used for starting daemons:

-a , -startas name Change the process name of the daemon to name This just changes the first argument passed to the daemon. -b , -background Force the daemon into the background. Some daemons don’t create pidfiles, so a good trick is to get the daemon to run in the foreground, and use the this option along with —m , -make-pidfile to create a working pidfile. -d , -chdir path chdir to this directory before starting the daemon. -r , -chroot path chroot to this directory before starting the daemon. All other paths, such as the path to the daemon, chdir and pidfile, should be relative to the chroot. -c , -chuid user Same as the —u , -user option. -e , -env VAR=VALUE Set the environment variable VAR to VALUE. -g , -group group Start the daemon as in the group. -k , -umask mode Set the umask of the daemon. -m , -make-pidfile Saves the pid of the daemon in the file specified by the —p , -pidfile option. Only useful when used with daemons that run in the foreground and forced into the background with the —-b , -background option. -I , -ionice class [: data ] Modifies the IO scheduling priority of the daemon. Class can be 0 for none, 1 for real time, 2 for best effort and 3 for idle. Data can be from 0 to 7 inclusive. -N , -nicelevel level Modifies the scheduling priority of the daemon. -1 , -stdout logfile Redirect the standard output of the process to logfile when started with —background Must be an absolute pathname, but relative to the path optionally given with —r , -chroot The logfile can also be a named pipe. -w , -wait milliseconds Wait milliseconds after starting and check that daemon is still running. Useful for daemons that check configuration after forking or stopping race conditions where the pidfile is written out after forking. -2 , -stderr logfile The same thing as —1 , -stdout but with the standard error output.

Читайте также:  Install yum linux centos

These options are only used for stopping daemons:

-R , -retry timeout | signal / timeout The retry specification can be either a timeout in seconds or multiple signal/timeout pairs (like SIGTERM/5).

ENVIRONMENT

SSD_IONICELEVEL can also set the IO scheduling priority of the daemon, but the command line option takes precedence.

SSD_NICELEVEL can also set the scheduling priority of the daemon, but the command line option takes precedence.

SSD_STARTWAIT As the —w , -wait option above. /etc/rc.conf waits for to check the daemon is still running.

NOTE

uses getopt(3) to parse its options, which allows it to accept the `—‘ option which will cause it to stop processing options at that point. Any subsequent arguments are passed as arguments to the daemon to start and used when finding a daemon to stop or signal.

SEE ALSO

BUGS

HISTORY

This is a complete re-implementation with the process finding code in the OpenRC library (librc, -lrc) so other programs can make use of it.

AUTHORS

Index

| |
— Powered by — Running on —
Copyright 2004-2020 Sascha Nitsch Unternehmensberatung GmbH
: :
— Level Triple-A Conformance to Web Content Accessibility Guidelines 1.0 —
— Copyright and legal notices —
Time to create this page: 16.2 ms

Источник

start-stop-daemon

В этой статье будет рассмотрено использование start-stop-daemon . Данная утилита идет в составе dpkg и, следовательно, присутствует в любой системе на базе Debian/Ubuntu.

Ее функция следующая: она позволяет запустить любой процесс в виде демона, то есть в фоне. Это нужно для того, чтобы запускать в фоне те процессы, которые сами не умеют уходить в фон. Запуск процесса в виде демона позволит не держать постоянной открытой tty-консоль или вкладку в терминале, а также даст больше возможностей для контроля данного процесса.

Читайте также:  Проброс портов linux ssh

Основы

Как упомянуто выше, основное предназначение — запуск программ в фоновом режиме. В качестве примера будет взят museekd , демон-клиент для p2p-сети soulseek. start-stop-daemon имеет два обязательных параметра: -S (или –start ) и -K ( –stop ), один из которых должен присутствовать в любой команде. Далее следуют параметры, указывающие, что и как запустить.

Запуск демона

Для того, чтобы запустить демон необходимо помимо ключа -S указать так же исполняемый файл – /usr/bin/museekd . Исполняемый файл задается ключом -x

start-stop-daemon -Sx /usr/bin/museekd

Однако, в фон программа не уйдет и вы увидите на экране ее вывод. Для того, чтобы процесс уходил в фон, нужно добавить ключ -b . Заодно добавьте ключ -v для отображения диагностических сообщений

start-stop-daemon -Sbvx /usr/bin/museekd

Программа запустится и будет работать в фоне. Для взятого примера этого достаточно.

Остановка демона

Для остановки процесса нужно указать ключ -K , т.е. действие «стоп», а так же сам процесс, который нужно остановить. Процесс для остановки так же указывается по исполняемому файлу, с помощью ключа -x

start-stop-daemon -Kvx /usr/bin/museekd

start-stop-daemon найдет процесс museekd и остановит его (по умолчанию — отправив SIGTERM).

Работа с pid-файлами

Если вы хотите запустить несколько копий одной программы, следует использовать pid-файлы 1) для управления такими процессами. Для запуска museekd с созданием pid-файла следует использовать ключ -p . Пример:

start-stop-daemon -Sbvmp $HOME/.museekd/pid -x /usr/bin/museekd

Здесь также появился ключ -m , указывающий утилите start-stop-daemon, что pid-файл нужно создать при запуске программы. Некоторые программы умеют создавать pid-файлы самостоятельно – в этом случае данный ключ не нужен.

Теперь в заданном файле записан PID запущенного процесса. Зная его, вы можете отличить его от других копий той же программы, найти процесс, к примеру, в top и сделать с ним что-либо (например, изменить приоритет или остановить).

Читайте также:  Kali linux создание установочной флешки

Для остановки процессов также можно использовать pid-файлы, чтобы остановить конкретный процесс. При этом указание исполняемого файла не требуется, нужно лишь задать действие «стоп» и pid-файл

start-stop-daemon -Kvp $HOME/.museekd/pid

start-stop-daemon прочитает PID из заданного файла, проверит, есть ли такой процесс и остановит его.

Прочие возможности

Передача параметров запускаемой программе

Если запускаемой программе нужно передать какие-либо параметры, они отделяются двумя дефисами. Все, что идет далее, не воспринимается как параметры для start-stop-daemon, а передается запускаемой программе в неизмененном виде. Пример запуска museekd с альтернативным файлом конфигурации:

start-stop-daemon -Sbvmx /usr/bin/museekd -p $HOME/.museekd/pid -- -c .museekd/config.new

Данная конструкция запустит museekd -c .museekd/config.new . Двойной дефис и следующие за ним параметры не обязательно располагать после исполняемого файла. Главное – в конце комманды.

Утилита start-stop-daemon имеет гораздо больше возможностей, чем описано в данной статье. Например, она позволяет запустить процесс от имени другого пользователя или даже в chroot-окружении, задать приоритет процесса, изменить сигнал остановки (например, использовать SIGKILL вместо SIGTERM) и т. п. Больше информации можно получить из man start-stop-daemon и start-stop-daemon –help .

PID – это уникальный номер, по которому идентифицируется каждый запущенный в системе процесс. По PID можно отличить разные копии одной программы. pid-файл — это простой текстовый файл, в который записывается PID процесса. pid-файлы для некоторых системных процессов можно найти в /var/run

  • Сайт
  • Об Ubuntu
  • Скачать Ubuntu
  • Семейство Ubuntu
  • Новости
  • Форум
  • Помощь
  • Правила
  • Документация
  • Пользовательская документация
  • Официальная документация
  • Семейство Ubuntu
  • Материалы для загрузки
  • Совместимость с оборудованием
  • RSS лента
  • Сообщество
  • Наши проекты
  • Местные сообщества
  • Перевод Ubuntu
  • Тестирование
  • RSS лента

© 2018 Ubuntu-ru — Русскоязычное сообщество Ubuntu Linux.
© 2012 Canonical Ltd. Ubuntu и Canonical являются зарегистрированными торговыми знаками Canonical Ltd.

Источник

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