文件名称:
Windows Services And Unix Daemons.pdf
开发工具:
文件大小: 153kb
下载次数: 0
上传时间: 2019-07-02
详细说明:Windows Services And Unix Daemons.pdfFigure 2: Threads and messages at runtime
Main thread
Sertice thread s
pp
lication
卫d山r1
Threa1 INstance
troller 2
Thresd
Rtsmced
工e兽
ManagER
r or -run, this will actually run the daemons. However, on windows, th
should never be used: the service manager will provide it automatically when
it needs to start a daemon
a daemon mapper is created. Only I daemon mapper should exist in the system. The
Lazarus IDE support ensures this is So
For each daemon definition present in the daemon mapper, the appropriate TCustomDaemon
descendent instance is created
What happens then depends on the command-line options: Either each of the in
stances is installed or uninstalled or the daemons are started by the service manager
(on windows)
If any daemons were started, the application will wait for them to finish, otherwise it
will exit
When running the daemons, the daemons are started in a separate thread: all code
daemon is run inside a separate thread, one thread per TCustomDaemon instance
m
main application thread runs a loop till all threads finish, and then terminates
Communication with the Windows Service manager happens through an extra class: TDaemon Controller
Under normal circumstances, it should never be needed to access the methods and proper-
ties of this class. However, people who want to extend the daemon support in Free Pascal
can make descendents of this class which have customized behaviour. When the appli-
cation creates all daemon instances. it creates an instance of Daemoncontroller for
each daemon. The windows service manager will communicate with this instance (this
communication happens in the main thread of the application), and the controller instance
delivers the message to the appropriate thread, so the daemon's reaction on the message
uns inside the context of the thread. figure2]on page 3]Shows this. The arrows show how
messages are sent. The simple lines are ownership relations
The functionality of the daemon must be implemented in a TCustomDaemon descende
The following methods exist
Start called when the daemon should start it's work. This method should return as soon
as possible, and return True if the work was started succesfull
Stop called when the daemon should stop it's work. This method should immediatly re
turn,and return True if the work was stopped succesfully
Shutdown called when the daemon should stop absolutely it's work. This method should
immediatly return, and must return True if the work was stopped succesfully. this
is called if the system is shutting down, and all services must be stopped
Pause called when the daemon should temporarily suspends it's activity. This method
should immediatly return, and return True if the work was suspended succesfully
Continue called when the daemon should resume it's activity after it was paused. This
method should immediatly return, and return True if the work was resumed succes
full
Install Called when the daemon must be registered as a(windows)service
UnInstall Called when the daemon must be unregistered as a(Windows)service
AfterUnInstall Called after the daemon was unregistered as a Windows service
Handle Custom Code is called when a the service manager sends a non-standard control
code( the code is passed in the ACode parameter to the handleCustomCode call)
In rare cases, the Execute method can be overridden: use this if no separate thread should
be started to run the daemon in
3 Creating a daemon application in code
To create a daemon application without using the visual support for it in Lazarus, the fol
lowing steps should be made
Create a ICustomDaemon descendent, and override any of the start, stop etc
method
2. Register the descendent with RegisterDaemonClass, so the daemon mapper
knows which class to instantiate
3. Create a descendent of TDaemonMapper which initializes the DaemonDefs col-
lection with correct daemon definitions
4. Register the descendent with RegisterDaemonMapper, so the application class
knows which mapper to instantiate
5. Run the application
To demonstrate this, a small daemon application is created. It does nothing useful, it sends
a tick message every second to the system logger and sends a message about every action
to the system logger
This action is achieved in a thread, which will be controlled by the daemon
fype
TTestThread Class(tHread)
Procedure Execute: override
n刁
procedure TTestThread Execute
C: - negeri
n
Repeat
Sleep(1000)i
inc(c)
Application Logger, Info(Format Tick od,[c]))i
Unti- Terminated
A most simple thread
Then the daemon which controls this thread is created
TTestDaemon - Class(TCustcmDaemon)
Private
EThread TTestThread
Procedure Threadstoppec (Sender TCbject)i
Functicn Start Boolean; override
Functicn stop Boolean; override
Functicn Pause Boolean; override
Functicn Continue Ecolean; override;
Functicn Execute Bocleani override
Functicn ShutDown Bcclean: override
Functicn Install Boclean; override
Functicn UrInstal-: bccleani override;
The start method looks like this
function TTestDaemon. Start:3。○1ean;
begin
Result:=inherited starti
AWriteln(daemon start Result)
FThread: -TTest Thread. Create(True)i
EThread. OnTerminate: - ThreadStopped
FThread. FreeOnTerminate: =Falsei
EThread. Resume
nd
As can be seen, it simply creates the TTestThread instance(with some housekeeping ), and
returns True. The Writeln simply
sage to the system logger
The stop method is quite simple, the thread is told to suspend it's action
function ttestDaen
e了1n
Resu t: =inherited stopi
teln(' daemon st
Result)
EThread. Terminate
en
The pause and continue functions hold no surprises
function tEstae
Pau
弓1ean
e91
Result: =inherited pause
WRiteln(' Daemon pause
Result)i
EThread Suspend
funct
TTestaemon Conti r
oean
Result: =inherited Continue
AWriteln( Daemon continue: Result)
EThread. Resume
The various install methods simply write a message to the system log
function TTestDaemon. Install: Boolean
Result: - inherited Install
AWriteln(' Daemon install: Result)i
end
The other methods are similar, they are not essential in this context.
The mapper class is equally simple
ype
TTestDaemonMappe
Class(TCus tomDaemonMapper)
Constructor Create(ACwner TComponent)i override
constructor TTestDaemonMapper Create(OWner: IComponent)i
Var
TDaemonDe f
己了n
herited create(Owner)
D: -DaemonDefs. dd as iDaemonDe f
D.Disp⊥ ayame:= Test daemon′
D. Name:=/ TestDae
D. Daemon1 assName:-′ TTestDaemon′
D. WinBindings Se
Type: =stwin32
It simply fills the definitions with a single daemon, and refers to the test class that was
ated abov
Remains to create the main program code:
Figure 3: The running daemon
□x
B·日口[00mcD1613cm+De:1lsrE,
6卜8曾则A国P冒=自固口
x
Fropcrbcs
4幽国囡回国图‖■
ISapptrpe c F% Services(Loca)
SR feel
Automaic
ESIFDEF
较IF][t
eEles a., 5ta
CF/-F NetBIOS Hel
t add you
ICvd=ss
cEmon
begin
RegisterDaemonclass(tTestDaenon)
RegisterDaemonMapper(TfestDaemonMapper)i
Application. Title: ='Daemon test applicatio
码pp⊥ -cation.Rn;
n彐
And thats it. To test this program on windows, first run it from the command-line(or from
within lazarus) with the command-line option -install. It will then appear in the list of
services(which can be consulted from the Services'menu entry under the Control panel
option Administrative Tools.)
The service manager can then be used to start the service: use a right-click on the Test
daemon service to call the context menu in the service manager and select 'Start,, to
see the effect of the daemon, the'Event viewer'application should be used (it can also be
found among the Administrative tools). In the application log, the Tick messages sent by
the daemon can be found. This is shown in figure]on page7
Under unix, the daemon can be run straight away with the -r option
4 Creating a daemon visually
The latest Lazarus versions in Sub version have support for designing daemons in the IDE
To enable this support, the Laz Daemon package must be installed in the IDE. If the pack-
age is supported, 3 items appear in the File- New dialog, under the heading Daemon
(Service) applications
Daemon(service) application this creates a new daemon application. It automatically
creates one MDaemon instance and a TDaemon Mapper instance. A registration
procedure for both the daemon and daemon mapper classes are created automaticall
Daemon module creates a new daemon instance
Daemon Mapper Creates a new TDaemon Mapper instance. Normally this should not be
used,as only one mapper should be created per application. Registering a second
mapper will result in an error
The daemon mapper can be used to define a daemon mapping: The DaemcnDe fs property
can be edited completely in the object inspector
The MDaemon module has events for all of the calls that exist in Tcust mdaemon:
Onstart, Onstop, On Shutdown, OnPause, OnContinue, OnbeforeInstall
OnAfterInstall, OnBeforeUnInstall, OnAfterUnInstall, onControlcode
To recreate the same daemon application with the Lazarus ide is very simple. The Daemon
service) application option should be chosen, the daemon can be renamed to
TestDaemon'and the mapper to TestMapper'. The TestDaemor can be added to the
DaemonDe-s property of the ' TestMapper'.(note that if the testdaenon module is re
named, the Daemonclassname property of the corresponding DaemonDef item is not
updated) After that, the daemon can be coded. The TTestThread can be added to the
TestDaemon unit, and the events can be coded The following code shows the OnStart
and On stop events
procedure TTestDaemon. TestDaernonstart (Sender: TCustomDaemon; var OK: Bcolean)i
e可1n
OK:=True
FThread: - Thread, Create(false)
FThread InTerminate: -dThreadstopped
THread. Freeonterminate:=False
THread Resume
procedure ITestDaemon TestDaemonstop(Sender: ICustomDaemor; var OK: Boclean)i
○eg1n
EThread. Terminate
endi
As can be seen the code is similar to the code of the non-visual coded daemon The rest of
the code can be found on the Cd accompagnying this issue.
Running the daemon on linux with the following command
/ daemon
工1n
will produce an output like this in the/var/log messages log file
8
Figure 4: The Service Control application
tus Editor v0 9.20 beta-srvmgrlpi
回
l區
Servce
Deendangiea
C Disabled
5-or Syalcm(: only
R⊥nnn
daend
22: 27: 48 home daemon: [Tnfo] Daemon Test. daemon current status: Start. Pend
Feb 1 22: 27: 48 home daemcr: [Info] Daemcn Test daemon current status: Running
Feb 1 22: 27:49 home daemon: [Info] Tick 1
Feb 1 22: 27: 50 home daemon: [Info] Tick 2
Feb 1 22: 27: 51 home daemon: [Info] Tick 3
Feb 1 22: 27: 52 home daemon: [Info] Tick 4
22: 27:53 home daemon: LInfo
Which is the equivalent of what could be observed under Windows
5 The Windows Service Manager component
In a previous article on using Delphi to write service applications for windows, the T Servicemanager
component was introduced. This component was ported to Free Pascal, and added to the
Free pascal distribution
The TServiceManager component was a component offering access to the Windows
Service manager APl, using an Object Oriented approach: it allowed to retrieve the defini-
tions and status of all services, register new services, plus offered the functionality which
the Service Manager application of Windows offers: starting and stopping services
The sample application which was presented then(a copy of the services control panel
applet), has been ported to Lazarus: This basically meant importing it via the lazarus
import functionality under the"Tools"menu, and recompiling it. The interested reader can
check the sources on the CD-ROM accompagnying this issue. In figure 4 on page9the
sample application can be seen, after compilation using lazarus
6 Conclusion
Creating cross-platform services is made easy using the daemonapp unit. The archi
tecture is quite extendible(a more Delphi-compatible extension is under way). It is not
entirely finished: Although the daemon can be paused, continued and stopped on Unix by
sending it the classical Unix signals STOP, CONT and TERM, it does not have quite the
same semantics as the Windows services: the onpause and oncontinue events will not be
triggered, as the kernel effectively pauses the application. Work is being done to create a
small control layer which provides the same possibilities as the windows version. However,
for Inost applications, the current functionality is sufficient to create services that can run
and do their work on both Windows and Unix platforms
10
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.