Daemons and Services/ru
│
English (en) │
español (es) │
français (fr) │
polski (pl) │
português (pt) │
русский (ru) │
Что такое демоны и службы?
Unix демоны и службы windows-программ, работают без взаимодействия с пользователем. Например, " " www"' или "'ftp"' серверы называются демонами под linux и службами под windows. Поскольку они не взаимодействуют с пользователем, они закрывают свои stdin, stdout, stderr дескрипторы при запуске.
Используя Free Pascal и Lazarus можно создавать демоны/службы в зависимости от платформы, используя пакет lazdaemon. Чтобы избежать конфликта имён с компонентами Delphi эти классы называются 'демонами' ('daemons').
Примечание: Поскольку материал данной статьи нацелен на кросс платформенное объяснение, то понятия «демон» и «служба» в ней означают одно и то же. Они не привязаны к какой либо ОС, если о том не оговорено заранее. Однако, необходимо понимать, что в разных ОС могут быть свои нюансы, которые могут быть не учтены в данной статье.
Установка LazDaemon
Прежде чем начать разработку службы или демона, установите пакет lazdaemon. Это можно сделать двумя способами: либо через пункт меню «Пакет/Установка и удаление пакетов» (Components / Configure installed packages), либо путем указания lpk файла из папки: lazarus/components/daemon/lazdaemon.lpk. Данный пакет устанавливает некоторые новые компоненты и элементы меню, в среде разработки (IDE).
Классы
TCustomDaemon
Данный класс реализует основную работу службы (демона) и является потомком TDataModule. Программа может использовать несколько классов TCustomDaemons и/или их экземпляров одновременно в одном процессе. Иными словами использовать много поточность в своей работе.
TCustomDaemonApplication
Класс TCustomApplication является потомком TCustomDaemon. Единственное отличие это класса от TCustomDaemon, что он работает под windows, пока не получит сигнал Stop или под linux до тех пор, пока не поступит сигнал TERM.
TDaemonMapper
Этот компонент выполняет регистрацию службы в системе. Каждый экземпляр службы должен быть указан в свойстве DaemonDefs.
Демоны(службы) - Пошаговая инструкция
- Когда демон запускается, ему могут быть переданы следующие параметры командной строки:
- -i --install: регистрация демона в системе. Данный параметр не доступен в unix.
- -u --uninstall: удаление регистрации демона в системе. Данный параметр не доступен в unix.
- -r --run: запуск демона. Windows, как правило запускает службу автоматически.
- Создайте объект, класса TDaemonMapper
- Для каждого пункта в свойстве DaemonDefs создайте объект, класса TCustomDaemon.
- Зарегистрируйте, удалите регистрацию в системе или запустите каждый созданный объект.
- Каждый объект запустится в своём собственном потоке. Дождитесь сигнала Stop или TERM для его завершения.
Daemon Methods
Start
Called when daemon should start. This method must return immediately with True.
Stop
Called when daemon should stop. This method must return immediately with True.
Shutdown
Called when daemon should be killed. This method must stop the daemon immediately and return with True. This is not triggered under Linux. Linux simply kills the daemon.
Pause
Called when daemon should pause. This method must return immediately with True. Under Linux this is not triggered because the kernel stops the whole daemon on STOP and continues it on CONT.
Continue
Called when daemon should continue after a pause. This method must return immediately with True. Under Linux this is not triggered.
Install
Called when daemon is registered as windows service. This method should return True on success.
Uninstall
Called when daemon is unregistered as windows service. This method should return True on success.
AfterUnInstall
Called after daemon was unregistered as windows service. This method should return True on success.
HandleCustomCode
Called when a special signal was sent to the daemon. This method should return True on success.
Getting Started
Before you are able to create a Service or Daemon application you must first ensure that the Lazarus Daemon package "lazdaemon" is installed.
Example
There is a simple example in examples/cleandir/. Read the README.txt.
Service Installation
Windows
You can install the service by executing the process with the Install parameter. Windows service manager will do the rest for you. You can configure the service and it's options from the service manager.
Linux (Debian)
Download, configure, and "Save As" - the sample script located at Service Script.
- SVC_ALIAS is the long description of your application
- SVC_FILENAME is the actual file name of your compiled service application
- SVC_DIR is the place your you copied the service application
- SVC_SERVICE_SCRIPT is the final name of the service.sh when you "Save As" the customized debian-service.sh script.
Place your script in the /etc/init.d/ folder
start the service by running "sudo service Name_Of_Your_Script start"
In order to auto-run the service at startup you can try update-rc.d or else will need a third party tool that will do this.
Option 1
sudo update-rc.d Name_Of_Your_Script defaults
Option 2
sudo apt-get install chkconfig
sudo chkconfig --add Name_Of_Your_Script
sudo chkconfig --level 2345 Name_Of_Your_Script on
Linux (Fedora)
Presently, linux flavors are trending away from differing daemon launching and into a unified service model.
Fedora uses systemd and with that commands to start/stop services are the same as on debian.
- From the command prompt sudo gedit
- Copy and Paste
[Unit]
Description=Long description of your application
After=network.target
[Service]
Type=simple
ExecStart=complete_path_and_file_name -r
RemainAfterExit=yes
TimeoutSec=25
[Install]
WantedBy=multi-user.target
- Edit the following values
- Description - Long Description of your service application
- ExecStart - complete-path_and_file_name is the name of your compiled service application with its complete path
- Save As Dialog
- Navigate to /lib/systemd/system/
- Name the file the name_of_your_service.service
A sample systemd config file can be found Service
See also
- ServiceManager Example for the FreePascal unit for managing Windows services
- Office Automation