Sign in Join
Wiki copytemporary

Daemons and Services: what changed

Revision 3 to 4. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## What are daemons, services and agents?
22
33Unix *daemons* and Windows *services* are system-wide programs running without user interaction; macOS *agents* are per user programs (cf system-wide daemons) that may or may not run without user interaction. Although the nomenclature differs, their function is similar: for example **www** or **ftp** servers are called daemons under Linux and services under Windows. Because they do not interact with the user directly, they close their stdin, stdout, stderr descriptors at start.
44
55With Free Pascal and Lazarus it is possible to write these daemons/services in a platform-independent manner using the Lazarus lazdaemon package. To avoid name conflicts with the Delphi components these classes are called 'daemons'.
66
77> **Note:** This page focuses on Windows and Linux. To read about Lazarus and macOS "Agents", please refer to [[macOS daemons and agents]].
88
99## Creating a Service/Daemon (using Lazarus and visual Components)
1010
1111> **Note:** The complete sample source code for this wiki page is available via the link at the end of this wiki page.
1212
1313### Prerequisite: Install the LazDaemon package
1414
1515Before you can start creating a daemon using the Lazarus IDE, you must install the LazDaemon package either via "Components" - "Configure installed packages" or by installing the lpk file directly from .../lazarus/components/daemon/lazdaemon.lpk. The package installs some new components and menu items in the IDE.
1616
1717![](/wiki-images/3/31/2022-02-21_14_34_28-LINDER-LAZW7_-_VMware_Workstation.png)
1818
1919Due to the way packages work in Lazarus, you need to "Save and rebuild the IDE" to install the LazDaemon package.
2020
2121### Creating and using scaffolded Daemon Project Files
2222
2323After having installed the LazDaemon package, from the "Project" - "New Project" Menu, pick "Daemon (service) application)".
2424
2525![](/wiki-images/e/ec/2022-02-17_16_31_12-Create_a_new_project.png)
2626
2727This will automatically create two units, one for a TDaemon descendant ("DaemonUnit"), and one for a TDaemonMapper descendant ("DaemonMapperUnit"), and a main project file ("TestDaemon.lpr"). This file needs a little change to work:
2828
2929``` pascal
3030Program TestDaemon;
3131
3232Uses
3333
3434// This is the scaffolded code, needs modification like shown below,
3535// since UseCThreads is usually not definied, and is not needed here
3636// {$IFDEF UNIX}{$IFDEF UseCThreads}
3737// CThreads,
3838// {$ENDIF}{$ENDIF}
3939
4040{$IFDEF UNIX}
4141 CThreads,
4242{$ENDIF}
4343 DaemonApp, lazdaemonapp, daemonmapperunit, DaemonUnit
4444 { add your units here };
4545
4646{$R *.res}
4747
4848begin
4949 Application.Initialize;
5050 Application.Run;
5151end.
5252```
5353
5454> **Warning:** The scaffolded .lpr file contains an additional {\$IFDEF UseCThreads} ... {\$ENDIF} clause (commented out in the sample above), which has been observed not to work, unless additional measures are taken to define UseCThreads. You can remove the conditional entirely or comment it out, like shown in the above .lpr sample, or add a -dUseCThreads option when you compile your daemon on Linux. Windows services are not affected.
5555
5656Despite that daemons don't have a GUI, both the DaemonApp and the DaemonMapper unit have support for the Lazarus Form Editor. This way you get a familiar GUI to populate the various properties of the daemon and the mapper class. Of course, if you prefer, you can initialize all properties in code as well like shown below.
5757
5858Both the scaffolded DaemonApp and the DaemonMapper unit contain a superfluous "var" definition (var DaemonMapper1: TDaemonMapper1; var Daemon1: TDaemon1;). Those are actually never used by the running daemon, they remain uninitialized, trying to access them results in an access violation fatal error. If you have a closer look at how daemon applications work internally you'll see that the code relies solely on the types (TDaemonMapper1, TDaemon), the vars can be ignored or removed entirely.
5959
6060The code provided by the TDaemon class does mainly respond to the various service control messages sent by the OS. The TDaemonMapper contains data structures describing the service. Both classes need to be registered with the daemon application framework, they will be used internally to configure the daemon when it starts. In this code sample registration is done in the "Initialization" section of each unit.
6161
6262The main "Application" object for a service-style application is introduced by putting a reference to DaemonApp into the uses section of each unit. In a daemon application, "Application" provides the complete service framework including advanced features like install and uninstall support, and logging. For the "worker" part of the daemon you are supposed to create a thread of its own, see sample code below, don't try to use the "Execute" method provided by the TDaemon class.
6363
6464### Populating the DaemonMapper Class
6565
6666For the moment let's just fill some basic properties to get things going. Note that the DaemonClassName must exactly match with what you have defined in the DaemonClass unit.
6767
6868![](/wiki-images/1/19/2022-01-31_23_32_52-Settings.png)
6969
7070> **Note:** For cross-platform programmers: In Unix everything is case-sensitive, using lowercase is common use, so you may cause some confusion if you define a mixed-case service name like shown in the above sample.
7171
7272Maybe have a short look into the WinBindings property, which lets you configure various service properties for use by the Windows Service Manager, like service start type and service user account. While not used for this basic demo daemon, setting those options properly is important for a real life daemon application. WinBindings doesn't have any effect on Linux, see the section about install and uninstall support for Linux on how to achieve the same for Linux by setting options in the systemd "unit" (.service) file.
7373
7474### Writing the Daemon Methods
7575
7676TDaemons support the following methods:
7777
7878| Method/Event | Description |
7979|----|----|
8080| `OnStart` | Called when daemon should start. This method must return immediately with *OK:=True*. |
8181| `OnStop` | Called when daemon should stop. This method must return immediately with *OK:=True*. |
8282| `OnShutDown` | Called when daemon should be killed, because the system shuts down. This method must stop the daemon immediately and return with *OK:=True*. This is not triggered under Linux. Linux simply kills the daemon process. |
8383| `OnPause` | Called when daemon should pause. This method must return immediately with *OK:=True*. Under Linux this is not triggered, instead the kernel stops the whole daemon on STOP. |
8484| `OnContinue` | Called when daemon should continue after a pause. This method must return immediately with *OK:=True*. Under Linux this is not triggered. |
8585| `OnExecute` | Do not use this property to implement the working code, use a worker task like shown in the code sample. |
8686| `BeforeInstall` | Called before service installation. |
8787| `AfterInstall` | Called after (successful) service installation. |
8888| `BeforeUninstall` | Called before service de-installation. |
8989| `AfterUninstall` | Called after successful service de-installation. |
9090| | |
9191
9292The following code snippets show all the major event handlers necessary to successfully implement a simple daemon. They have been tested on Windows 7/10/11 and several Linux distros (Debian 10.8 and Ubuntu 20.04.3).
9393
9494Some handy helper functions have been offloaded into separate units, so they do not obfuscate the daemon core code:
9595
9696- FileLoggerUnit: a thread safe log to file helper. It is required because the control signal receiver included in the TDaemon application and the service's working code need to be implemented as separate threads, otherwise the daemon will not respond to control signals while the service worker code runs. So in any daemon there are at least two tasks involved, which could create a clash when accessing the log file simultaneously. See the Lazarus wiki [[Multithreaded Application Tutorial]] for details about how to serialize accesses to a single resource by using a TRTLCriticalSection to make the code thread-safe. The FileLoggerUnit code does always write the log into the program directory, please make sure the daemon has write access permissions. The code writes one file per day, the filename contains the creation date. If you need a more sophisticated logger, consider using the [[LazLogger]] unit.
9797- [DaemonWorkerThread](https://gitlab.com/freepascal.org/lazarus/lazarus/-/tree/main/examples/TDaemon): a TThread descendant class to hold the daemon "worker" code. See the Lazarus wiki [[Multithreaded Application Tutorial]] for details about the TThread.Execute method containing the inevitable "while not terminated" loop. There is nothing special with a worker thread initiated by a TDaemon, it's just a simple thread like any other.
9898- [DaemonSystemdInstallerUnit](https://gitlab.com/freepascal.org/lazarus/lazarus/-/tree/main/examples/TDaemon): a unit which tries to provide support for the -install and -uninstall command line parameters for Linux. Adds systemd/systemctl support by writing an appropriate control file to /lib/systemd/system.
9999
100100### Daemon Start/Stop Signal Handler
101101
102102``` Pascal
103103// ---------------------
104104// Start and Stop signal
105105// ---------------------
106106
107107procedure TDaemon1.DataModuleStart(Sender: TCustomDaemon; var OK: Boolean);
108108begin
109109 LogToFile(Format('Daemon received start signal, PID:%d', [GetProcessID]));
110110 // Create a suspended worker thread - see DaemonWorkerThread unit
111111 FDaemonWorkerThread := TDaemonWorkerThread.Create;
112112 // Parametrize it
113113 FDaemonWorkerThread.FreeOnTerminate := False;
114114 // Start the worker
115115 FDaemonWorkerThread.Start;
116116 OK := True;
117117end;
118118
119119procedure TDaemon1.DataModuleStop(Sender: TCustomDaemon; var OK: Boolean);
120120begin
121121 LogToFile('Daemon received stop signal');
122122 // stop and terminate the worker
123123 if assigned(FDaemonWorkerThread) then
124124 begin
125125 FDaemonWorkerThread.Terminate;
126126 // Wait for the thread to terminate.
127127 FDaemonWorkerThread.WaitFor;
128128 FreeAndNil(FDaemonWorkerThread);
129129 end;
130130 LogToFile('Daemon stopped');
131131 OK := True;
132132end;
133133```
134134
135135These handlers deal with the start and stop signals issued by the operating system. If the daemon starts, DataModuleStart fires and we spawn the "worker" thread found in the DaemonWorkerThread unit, see the TDeamonWorkerThread.Execute method to find the actual working code of our daemon. To understand the thread code, refer to the [[Multithreaded Application Tutorial]] wiki page and to the documentation of TThread.
136136
137137> **Warning:** To implement the daemon worker code, one might consider to implement a handler for the "execute" method found in TDaemon. This does not work well, especially not on WIndows. Execute does not run as a separate thread, while it executes the daemon stops handling control messages. The daemon will start and run fine, but if you try to stop/pause/resume it using the Windows Service Manager or the sc command, the daemon will not respond and appear to hang.
138138
139139### Daemon Shutdown Handler
140140
141141This Windows-only handler is called when the daemon is to be stopped because of an operating system shutdown. If we do not handle the event, Windows will simply forcefully kill the daemon process, potentially corrupting open files. For this simple demo service one can simply call the DataModuleStop event handler, executing the same code like a normal service stop. On Linux this handler is not supported, Linux will instead directly call the stop handler.
142142
143143``` Pascal
144144procedure TDaemon1.DataModuleShutDown(Sender: TCustomDaemon);
145145// Supported on Windows systems only
146146begin
147147 self.Stop; // On shutdown, we trigger the stop handler. This will do nicely for this demo
148148 LogToFile('Daemon received shutdown signal');
149149end;
150150```
151151
152152### Install and Uninstall for Linux (systemd)
153153
154154The built-in install and uninstall support (-install and -uninstall command line parameters) is implemented in LazDaemon applications for Windows only. Here is a simple code sample showing how to make custom handlers for install and uninstall events to add a similiar functionality for Linux.
155155
156156``` Pascal
157157// --------------------------------
158158// Installation and De-Installation
159159// --------------------------------
160160
161161procedure TDaemon1.DataModuleAfterInstall(Sender: TCustomDaemon);
162162
163163 var
164164 isInstalled: boolean = True;
165165 FilePath: string;
166166
167167begin
168168 LogToFile('Daemon installing');
169169 {$IFDEF UNIX}
170170 FilePath := GetSystemdControlFilePath(Self.Definition.Name);
171171 isInstalled := CreateSystemdControlFile(self, FilePath);
172172 if not isInstalled then
173173 LogToFile('Error creating systemd control file: ' + FilePath);
174174 {$ENDIF}
175175 if isInstalled then
176176 LogToFile('Daemon installed');
177177end;
178178
179179procedure TDaemon1.DataModuleBeforeUnInstall(Sender: TCustomDaemon);
180180 var
181181 isUnInstalled: boolean = True;
182182 FilePath: string;
183183
184184 begin
185185 LogToFile('Daemon uninstalling');
186186 {$IFDEF UNIX}
187187 FilePath := GetSystemdControlFilePath(Self.Definition.Name);
188188 isUnInstalled := RemoveSystemdControlFile(FilePath);
189189 if not isUninstalled then
190190 LogToFile('Error removing systemd control file: ' + FilePath);
191191 {$ENDIF}
192192 if isUninstalled then
193193 LogToFile('Daemon uninstalled');
194194 end;
195195```
196196
197197These Unix/Linux-only handlers utilize the routines in DaemonSystemdInstallerUnit to write a systemd control file (.service file) for our service to /lib/systemd/system, so the daemon can be controlled using the systemctl command. On uninstall, the .service file ist deleted.
198198
199199If you don't specify a user account in the .service file, systemd will run the daemon as root. Running a daemon as "root" (Linux) or "LocalSystem" (Windows) is, for security reasons, considered bad practice, and can, amongst many other obstacles, hamper debugging the running daemon. Consider to add a line
200200
201201``` Pascal
202202 [...]
203203 f.WriteString('Service', 'Type', 'simple');
204204 f.WriteString('Service', 'User', '...'); // insert a service account here, otherwise the daemon will run as root
205205 f.WriteString('Service', 'ExecStart', Application.ExeName + ' -r');
206206 [...]
207207```
208208
209209in the DaemonSystemdInstallerUnit.CreateSystemdControlFile code.
210210
211211> **Note:** At runtime you'll find all the TDaemonMapper and especially the TDaemonMapper.WinBindings settings in the "self.Definition" and "self.Definition.WinBindings" structures. If you prefer, you may consider using some of them to populate settings in the .service file.
212212
213213For a comprehensive guide on all settings available in a systemd .service file (sometimes called a systemd "unit file") please see the documentation of your Linux distribution.
214214
215215### Daemon Worker Thread
216216
217217At the core of every daemon there is a piece of code which does the actual work, I named it the "worker" thread. It needs to be a separate thread, because in the background the daemon is supposed to continue to listen for control messages and process them. Creation and destruction of the thread can be seen in the above samples for TDaemon.DataModuleStart and TDaemon.DataModuleStop handlers.
218218
219219``` Pascal
220220procedure TDaemonWorkerThread.Execute;
221221
222222var
223223 i: integer;
224224
225225begin
226226 LogToFile('Daemon worker thread executing');
227227 while not Terminated do
228228 begin
229229 // placeholder, put your actual service code here
230230 // ...
231231 LogToFile('Daemon worker thread running');
232232 // Thread- and CPUload friendly 5s delay loop
233233 for i := 1 to 50 do
234234 begin
235235 if Terminated then break;
236236 Sleep(100);
237237 end;
238238 // ...
239239 // ----------------------------------------
240240 end;
241241 LogToFile('Daemon worker thread terminated');
242242end;
243243```
244244
245245This "worker" doesn't do much, it loops until terminated and writes a message into the log every 5 seconds.
246246
247247For your own daemon functionality, replace the code between "..." and "..." with your own.
248248
249249The inner loop of a TThread.Execute method must be layed out in a way so it checks the "Terminated" flag frequently. The flag is set by the TThread.Terminate method which is called to gracefully end a thread execution, like it can be seen in the above TDaemon.DataModuleStop sample. There is more info about TThreads available in the [[Multithreaded Application Tutorial]] wiki.
250250
251251To keep the sample demo code simple, it does not handle runtime errors in any way. Errors in the logging unit will be dropped silently, all other runtime errors in the daemon will crash the daemon. Please refer to the wiki page about [[Exceptions]] to read more about catching and handling exceptions in general, and see the documentation on TThread.HandleException to read more about how to properly catch and forward an exception within the execute method of a worker thread.
252252
253253### Initializing TDaemon Properties in Code
254254
255255If you prefer not to use the Lazarus IDE and its Forms Editor to populate your TDaemon and TDeamonMapper properties, you can do it all in code as well. If you want to go this route, note that your project must not be based on the LCL/Forms like other applications, but on DaemonApp. Failing this will make the code fail with numerous stream loading errors.
256256
257257Working with TDaemon (The event driven approach to program a daemon) has already been described in the above sections, the only real difference is that you will assign the event handlers in the application code like so:
258258
259259``` Pascal
260260TDaemon1 = class(TDaemon)
261261 {...}
262262 procedure DataModuleStart(Sender: TCustomDaemon; var OK: Boolean); // sample event handler event
263263 {...}
264264public
265265 constructor Create(AOwner: TComponent); override; // overwrite the constructor to initialize the event handlers
266266end;
267267
268268{...}
269269
270270constructor TDaemon1.Create(AOwner: TComponent);
271271begin
272272 inherited Create(AOwner);
273273 {...}
274274 onStart := @DataModuleStart; // assign the sample event handler code
275275 {...}
276276end;
277277```
278278
279279Follow the same strategy with TDaemonMapper to populate the Mapper.
280280
281281> **Note:** If you prefer an OOP based approach using inheritance to customize the daemon- and the mapper class you can do this as well, inherit your own daemon from TCustomDaemon and your own mapper from TCustomDaemonMapper, and overwrite the various virtual functions in the "Protected" section as needed
282282
283283Here is an excerpt from the DaemonApp unit showing the available properties:
284284
285285``` Pascal
286286 TCustomDaemon = Class(TDataModule)
287287 private
288288
289289 [...]
290290
291291 Protected
292292 Function Start : Boolean; virtual;
293293 Function Stop : Boolean; virtual;
294294 Function Pause : Boolean; virtual;
295295 Function Continue : Boolean; virtual;
296296 Function Execute : Boolean; virtual;
297297 Function ShutDown : Boolean; virtual;
298298 Function Install : Boolean; virtual;
299299 Function UnInstall: boolean; virtual;
300300
301301 [...]
302302```
303303
304304## Creating a Service/Daemon (in Code only)
305305
306306> **Note:** The complete sample source code for this wiki page is available via the link at the end of this wiki page.
307307
308308TestDaemonCodeOnly is a demo project utilizing the TCustomDaemon and TCustomDaemonMapper classes, and it works without the Lazarus IDE. It does therefore not need any Lazarus specific helper files like .lpr or .lfm, and can be maintained using any plain text editor. The programming paradigm used is not event-driven like in GUI centric code, but works based on OOP and inheritance. The helper units providing file logging, a daemon worker thread and support for systemd -install and -uninstall for Linux are the same as in the above GUI sample.
309309
310310Support for -install and -uninstall for Linux is provided by the same DaemonSystemdInstallerUnit as used above. Windows service installation and uninstallation is already built-in in the DaemonApp unit. The TDaemonMapper class provides the WinBindings property to configure the service for Windows, on Linux this property is not used and has no effect. The code provided in the DeamonSystemdInstallerUnit provides similar functionality for Linux/systemd/systemctl.
311311
312312The -run parameter is not supported on Windows, Windows has its own facilities (the Windows Service Control Manager or the "sc" command line tool) to control services.
313313
314314The daemon code needs to be implemented in multiple threads, one for handling the daemon control messages and a separate thread for the daemon "worker" code. Just overwriting the TCustomDaemon.Execute method won't work well, since while the daemon loops in the "TDaemon.Execute" method it will not handle control messages. It will therefore appear to hang in the Service Control Manager and refuse to respond to sc commands. The "worker" thread code is identical with what's required in the above GUI sample, and implemented in the DaemonWorkerThread unit.
315315
316316The absence of a GUI and console requires the use of a logging facility. The TCustomDaemon object provides a logging facility (through the EventLog property), but that is not thread-safe. The FileLoggerUnit provides a simple thread-safe log to file facility. For more sophisticated logging, consider to use the [[LazLogger]] unit.
317317
318318> **Warning:** The logfile created by the FileLoggerUnit is written to the program directory, please ensure that the dameon has write access to it.
319319
320320For more detailed informations about multithreading and how to make code thread-safe through the use of CriticalSections see the [[Multithreaded Application Tutorial]].
321321
322322``` Pascal
323323program TestDaemonCodeOnly;
324324
325325{$mode objfpc}{$H+}
326326
327327uses
328328 {$IFDEF UNIX}
329329 cthreads,
330330 {$ENDIF}
331331 Classes,
332332 SysUtils,
333333 { you can add units after this }
334334 DaemonApp,
335335 FileLoggerUnit, // Thread safe file logger
336336 DaemonWorkerThread, // a TThread descendant to do the daemon's work
337337 DaemonSystemdInstallerUnit; // -install and -uninstall support for Linux/systemd
338338
339339// ------------------------------------------------------------------
340340// TDaemonMapper: This class type defines the settings for the daemon
341341// ------------------------------------------------------------------
342342
343343type
344344 TDaemonMapper1 = class(TCustomDaemonMapper)
345345 public
346346 constructor Create(AOwner: TComponent); override;
347347 end;
348348
349349 constructor TDaemonMapper1.Create(AOwner: TComponent);
350350
351351 begin
352352 inherited Create(AOwner);
353353 with TDaemonDef(self.DaemonDefs.Add) do
354354 begin
355355 DaemonClassName := 'TDaemon1'; // This must exactly match the daemon class
356356 Name := 'TestDaemonCodeOnly'; // Service name
357357 DisplayName := 'Test Daemon (CodeOnly)'; // Service display name
358358 Description := 'Lazarus Daemons and Services Wiki Demo Service (Created in Code only)';
359359 Options := [doAllowStop, doAllowPause];
360360 WinBindings.StartType := stManual; // stBoot, stSystem, stAuto, stManual, stDisabled
361361 WinBindings.ServiceType := stWin32;
362362 end;
363363 end;
364364
365365// -------------------------------------------------------------------
366366// TDaemon: This class type definies the daemon task and handles the
367367// events triggered by the Windows/Linux Service Manager
368368// -------------------------------------------------------------------
369369
370370type
371371
372372 { TDaemon1 }
373373
374374 TDaemon1 = class(TCustomDaemon)
375375 private
376376 FDaemonWorkerThread: TDaemonWorkerThread;
377377 public
378378 function Start: boolean; override; // start the daemon worker thread
379379 function Stop: boolean; override; // stop the daemon worker thread
380380 function Pause: boolean; override; // pause the daemon worker thread (Windows only)
381381 function Continue: boolean; override; // resume the daemon worker thread (Windows only)
382382 function ShutDown: boolean; override; // stop the daemon worker thread because of OS shutdown
383383 function Install: boolean; override; // added -install suppport for Linux
384384 function UnInstall: boolean; override; // added -uninstall suppport for Linux
385385 end;
386386
387387 { TDaemon1 }
388388
389389 // ------------------------------------------------
390390 // Daemon start and stop signal
391391 // ------------------------------------------------
392392
393393 function TDaemon1.Start: boolean;
394394 begin
395395 // Create a suspended worker thread - see DaemonWorkerThread unit
396396 FDaemonWorkerThread := TDaemonWorkerThread.Create;
397397 // Parametrize it
398398 FDaemonWorkerThread.FreeOnTerminate := False;
399399 // Start the worker
400400 FDaemonWorkerThread.Start;
401401 LogToFile(Format('TDaemon1: service %s started, PID=%d', [self.Definition.Name, GetProcessID]));
402402 Result := True;
403403 end;
404404
405405 function TDaemon1.Stop: boolean;
406406 begin
407407 // stop and terminate the worker
408408 if assigned(FDaemonWorkerThread) then
409409 begin
410410 FDaemonWorkerThread.Terminate;
411411 // Wait for the thread to terminate.
412412 FDaemonWorkerThread.WaitFor;
413413 FreeAndNil(FDaemonWorkerThread);
414414 end;
415415 Result := True;
416416 LogToFile(Format('TDaemon1: service %s stopped', [self.Definition.Name]));
417417 end;
418418
419419// ------------------------------------------------
420420// Daemon pause and continue signal (Windows only)
421421// ------------------------------------------------
422422
423423 function TDaemon1.Pause: boolean;
424424 begin
425425 FDaemonWorkerThread.Suspend; // deprecated, yet still working
426426 LogToFile(Format('TDaemon1: service %s paused', [self.Definition.Name]));
427427 Result := True;
428428 end;
429429
430430 function TDaemon1.Continue: boolean;
431431
432432 begin
433433 LogToFile(Format('TDaemon1: service %s continuing', [self.Definition.Name]));
434434 FDaemonWorkerThread.Resume; // deprecated, yet still working
435435 Result := True;
436436 end;
437437
438438// --------------------------------------------------------------
439439// Daemon stop on operating system shutdown signal (Windows only)
440440// --------------------------------------------------------------
441441
442442 function TDaemon1.ShutDown: boolean;
443443 begin
444444 Result := self.Stop; // On shutdown, we trigger the stop handler. This will do nicely for this demo
445445 LogToFile(Format('TDaemon1: service %s shutdown', [self.Definition.Name]));
446446 end;
447447
448448// -----------------------------------------------------------------------------------------
449449// Daemon install and uninstall helpers for Linux, Windows is already built in TCustomDaemon
450450// -----------------------------------------------------------------------------------------
451451
452452 function TDaemon1.Install: boolean;
453453
454454 var
455455 FilePath: string;
456456
457457 begin
458458 Result := False;
459459 {$IFDEF WINDOWS}
460460 Result := inherited Install;
461461 {$ELSE}
462462 {$IFDEF UNIX}
463463 FilePath := GetSystemdControlFilePath(Self.Definition.Name);
464464 LogToFile(Format('TDaemon1: installing control file: %s',[FilePath]));
465465 Result := CreateSystemdControlFile(self, FilePath);
466466 if not Result then
467467 LogToFile('TDaemon1: Error creating systemd control file: ' + FilePath);
468468 {$ENDIF}
469469 {$ENDIF}
470470 LogToFile(Format('TDaemon1: service %s installed: %s', [self.Definition.Name, BoolToStr(Result, 'ok', 'failure')]));
471471 end;
472472
473473 function TDaemon1.UnInstall: boolean;
474474
475475 var
476476 FilePath: string;
477477
478478 begin
479479 Result := False;
480480 {$IFDEF WINDOWS}
481481 Result := inherited UnInstall;
482482 {$ELSE}
483483 {$IFDEF UNIX}
484484 FilePath := GetSystemdControlFilePath(Self.Definition.Name);
485485 Result := RemoveSystemdControlFile(FilePath);
486486 if not Result then
487487 LogToFile('TDaemon1: Error removing systemd control file: ' + FilePath);
488488 {$ENDIF}
489489 {$ENDIF}
490490 LogToFile(Format('TDaemon1: service %s uninstalled: %s', [self.Definition.Name, BoolToStr(Result, 'ok', 'failure')]));
491491 end;
492492
493493// ---------------------
494494// Daemon main init code
495495// ---------------------
496496
497497begin
498498 RegisterDaemonClass(TDaemon1);
499499 RegisterDaemonMapper(TDaemonMapper1);
500500 Application.Run;
501501end.
502502```
503503
504504## Daemon/Service Installation
505505
506506### Windows
507507
508508You can install the service from any elevated command prompt by starting the executable with the -install parameter.
509509
510510Open a terminal with elevated privileges (run as administrator), navigate to the directory where you compiled your test application into, and try the following commands:
511511
512-<thead>
513-
514-</thead>
515-<tbody>
516-
517-when the machine boots</td>
518-
519-</tbody>
512+| Command | Description |
513+|---|---|
514+| `TestDaemon -install` | install the daemon |
515+| `sc query TestDaemon` | check the service status |
516+| `sc config TestDaemon start=auto` | configure the service to be started · when the machine boots |
517+| `sc config TestDaemon start=manual` | configure the service to be started manually |
518+| `sc config TestDaemon start=disabled` | disable the service (cannot be started manually) |
519+| `TestDaemon -uninstall` | remove the daemon |
520520
521521![](/wiki-images/a/a4/2022-01-31_23_50_28-Lazarus_IDE_v2.2.0RC2_-_Daemon_application.png)
522522
523523After successful installation you can control the service either via the sc command line, or by GUI using the "Services" management console. Recent Windows Versions do also have a basic service control facility on the "Services" tab of the Task Manager.
524524
525525The most important sc commands to control a service after installation are:
526526
527527| Command | Description |
528528|-----------------------|-------------------------|
529529| `sc start TestDaemon` | start the service |
530530| `sc query TestDaemon` | query the service state |
531531| `sc stop TestDaemon` | stop the service |
532532
533533You may also use the Windows service control manager console.
534534
535535![](/wiki-images/0/07/ServiceControlManager.png)
536536
537537> **Note:** Most Windows service properties, like autostart on boot or usage of a specific service account, can be set via the TDaemonMapper1.WinBindings property in the DaemonMapperUnit1 file.
538538
539539### Linux
540540
541541Unlike for Windows, the TDaemonApp application does not have any support for an automated installation, since under Linux/Unix there is a wide variety of service control subsystems. You can implement your own installation scripts in the install and uninstall handlers of the TCustomDaemon object, like shown for systemd support in the above code sample. If you follow that route, installation and de-installation is essentially the same like on Windows.
542542
543543You can install and uninstall the service from a terminal by starting the executable with sudo and the -install or -uninstall parameter:
544544
545-<thead>
546-
547-</thead>
548-<tbody>
549-
550-when the machine boots</td>
551-
552-when the machine boots</td>
553-
554-</tbody>
545+| Command | Description |
546+|---|---|
547+| `sudo ./TestDaemon -install` | install the service |
548+| `sudo ./TestDaemon -uninstall` | uninstall the service |
549+| `systemctl enable TestDaemon` | configure the service to be started · when the machine boots |
550+| `systemctl disable TestDaemon` | configure the service to not be started · when the machine boots |
555551
556552After successful installation you can control the service using the systemctl command
557553
558554| Command | Description |
559555|-------------------------------|-------------------------|
560556| `systemctl start TestDaemon` | start the service |
561557| `systemctl status TestDaemon` | query the service state |
562558| `systemctl stop TestDaemon` | stop the service |
563559
564560![](/wiki-images/4/4f/OnLinuxWithSystemctl.png)
565561
566562The code in DaemonSystemdInstallerUnit.CreateSystemdControlFile triggered by the -install command line parameter reads the most basic properties of the TDaemonMapper class and writes a simple systemd .service file into the /lib/systemd/system directory to put your daemon under control of systemd. If you prefer to do it manually, you may use any text editor to create your own file following this template:
567563
568564``` ini
569565[Unit]
570566Description=Long description of your application
571567After=network.target
572568
573569[Service]
574570Type=simple
575571User=name_of_a_service_user_account
576572ExecStart=complete_path_and_file_name -r
577573RemainAfterExit=yes
578574TimeoutSec=25
579575
580576[Install]
581577WantedBy=multi-user.target
582578```
583579
584580- Edit the following values
585581 - Description - Long Description of your service application
586582 - ExecStart - complete-path_and_file_name is the name of your compiled service application with its complete path
587583 - User - specify an service user account here, if omitted the daemon will run as root, running a daemon as root is strongly discouraged
588584
589585- Save the file
590586 - Navigate to /lib/systemd/system/
591587 - Name the file the name_of_your_service.service
592588
593589Many more entries in the .service file created by DaemonSystemdInstallerUnit.CreateSystemdControlFile are available to customize how systemd controls your daemon, please see the the systemd "unit" file reference of your Linux distribution.
594590
595591## Reading the Log File
596592
597593This is a sample log file showing the daemon's internals while running, it was created on Windows, but will look exactly the same on Linux.
598594
599595![](/wiki-images/d/d1/2022-02-01_12_17_27-TestDaemon.png)
600596
601597> **Warning:** The FileLoggerUnit does always log into the program directory, please make sure the daemon has write access permissions to it.
602598
603599## Debugging a Daemon/Service
604600
605601Debugging a daemon is not as straightforward as debugging a normal application, since a running daemon does usually have neither a GUI nor a console, and its run/stop state is usually managed by the operating system. Windows and Linux require different approaches to debugging, especially to the way you initiate a debugging session. Once you have attached the debugger to the daemon and hit your first breakpoint, things work just with any other application, and you may control the debugger directly from your Lazarus GUI and the daemon source code.
606602
607603As a prerequisite, you need to compile your service/daemon using a "debug" configuration, so debug code gets inserted and a matching debug symbol file (.dbg) file is created.
608604
609605### Windows
610606
611607The debugging strategy on Windows depends on what portion of the code you need to examine:
612608
613609\- If you need to debug -install or -uninstall, set "Run" - "Run Parameters" in the Lazarus GUI to -install or -uninstall, set your breakpoints, and start the code \[F9\].
614610
615611\- If you need to debug the service worker code, start the service via the operating system (sc command or Windows Service Manager), determine the Process ID (PID), and then choose "Run" - "Attach to Program". Once attached, the debugger will automatically halt at a predefined temporary breakpoint in ntdll.dll!DbgUserBreakPoint, and the service will be looping somewhere within the worker code. After setting your breakpoints and watches in the worker code, resume your debugging by running the code using \[F9\].
616612
617613![](/wiki-images/d/da/2022-02-21_21_25_22-Lazarus_IDE_v2.2.0_-_Daemon_application_%28debugging_...).png "2022-02-21_21_25_22-Lazarus_IDE_v2.2.0_-_Daemon_application_(debugging_...).png")
618614
619615> **Warning:** The "Pause" button in the Lazarus symbol bar does not seem to work when debugging a running process remotely, it will hang the debugger if pressed. Use "Run" \[F9\] to resume debugging after a breakpoint.
620616
621617\- If you need to debug the create or start handlers, or any other piece in code which might have already been executed before you had a chance to "Attach to program" you can make your code wait until a debugger is attached by inserting the following line in your code:
622618
623619``` Pascal
624620// This code will loop until a debugger is attached
625621While not IsDebuggerPresent do sleep(100); // will loop until a debugger is attached
626622// ... put a breakpoint somewhere after the loop to catch the code as soon as it leaves the loop
627623```
628624
629625![](/wiki-images/c/c4/2022-02-21_21_36_38-Lazarus_IDE_v2.2.0_-_Daemon_application_%28debugging_...).png "2022-02-21_21_36_38-Lazarus_IDE_v2.2.0_-_Daemon_application_(debugging_...).png")
630626
631627After attaching the debugger and pressing \[F9\] the daemon will stop right at the breakpoint.
632628
633629> **Note:** The -run parameter supported by Linux is not available on Windows. You must use the Windows Service Control Manager to start and stop the service. To attach the debugger to the then running process you need to run the Lazarus IDE with Administrative Prvilege (elevated), otherwise you will get Error 5 (access denied) when trying to attach to the service. If you are running Lazarus elevated, and nevertheless have difficulties attaching to your service ("Access denied" or "Run" - "Attach to program" is grayed out) make sure you have set the debugger in "Project" - "Project Settings" - "Debugger" properly, most likely you will need "Gdb (Gnu Debugger)".
634630
635631### Linux
636632
637633Linux is propably somewhat easier to debug, since you can execute your daemon like every other program from within the Lazarus IDE, if you enter -run into "Command line parameters" in the "Run" - "Run Parameters" menu. Keep in mind though, that many problems originate from security restrictions enforced by the operating system. Many of those restrictions are not applied when the daemon is run in user context.
638634
639635![](/wiki-images/f/fd/2022-02-22_12_18_20-Debian_10.8_Buster_-_VMware_Workstation.png)
640636
641637Now you can start the daemon using \[F9\] like any normal application and debug it.
642638
643639![](/wiki-images/e/e9/2022-02-22_12_19_41-Debian_10.8_Buster_-_VMware_Workstation.png)
644640
645641If you do, for instance because you suspect a problem with service specific restrictions, need to attach the debugger to the already running daemon, you can do so using "Run" - "Attach to Program", if you have configured the daemon to run under a specific user account instead of root. See the chapter above about Linux install and uninstall support on how to add an appropriate option to the .service file.
646642
647643Unfortunately there isn't such a handy "IsDebuggerPresent" call available like under Windows, but the following trick works nicely.
648644
649645``` Pascal
650646procedure WaitForDebugger;
651647
652648var
653649 SetMeValue:boolean=false;
654650
655651begin
656652 // Linux trick: attach the debugger, and change SetMeValue to true
657653 while not SetMeValue do
658654 sleep(100); // put a breakpoint here
659655end;
660656```
661657
662658Put a breakpoint into the line with the "sleep" command. Once the daemon is started using systemctl, execution it will be halted at your breakpoint in the while loop. Now you can attach the debugger to the PID you got from systemctl status, put a watch (\[Ctrl-F5\]) on the "SetMeValue" variable and then use the Evaluate/Modify context menu to change the value of the "SetMeValue" variable from "false" to "true", and resume program execution (\[F9\]). The execution will immedately leave the while loop and run to the next breakpoint.
663659
664660## Known problems
665661
666662### Permission related Problems
667663
668664While you can do most of the development of the core daemon code under a user account and from within an IDE (Lazarus), the live daemon will most likely run "in the background" under a different context. Nowadays operating systems do, for security reasons, run daemons in more or less restricted environments. Because a daemon does have neither a terminal nor a GUI to show any messages, debugging such issues can be hard. Unfortunately there is no common recipe which resolves all service related problems in all operating systems supported by FPC/Lazarus, as the strategy behind restricting service code is vastly different between Windows, Linux and macOS, and it is even changing between different versions of the same operating system, with the more recent versions trending to be more restrictive than their predecessors.
669665
670666If you make the transition from running the daemon code under your developer account to "go live" and test the daemon running under a service user account oder under "Localsystem" or "root" (which, btw, is considered bad security practice since many years), take the time to study the security related documentations of your operating system and find out which restrictions and other specialities apply if code runs in the background.
671667
672668> **Note:** See the section above about debugging daemons running in the background by attaching the debugger to the running code. Make your daemon, once the daemon is started by the operating system, wait until the debugger is attached. From there you can then observe the execution and detect restrictions related exceptions and other security/background operation related nastinesses.
673669
674670### Exception EStreamError: "no streaming method available"
675671
676672```text
677673Exception at 0041A30E: EStreamError:
678674Failed to initialize component class "TDaemon1": No streaming method available.
679675```
680676
681677You have included visual components (which require initalization by a built-in resource stream created by the .lfm file in GUI applications) in a code-only daemon project. If you decide to create the daemon in code, you may neither include the LazDaemon package, nor add the "LazDaemonApp" to the uses section. If you do, your project will compile fine, but if you start the exe you get the above error.
682678
683679### Several "Stream Read" and "Unkown Properties" errors ...
684680
685681... when loading a daemon project through the Lazarus IDE.
686682
687683Most likely you try to open a TDaemon (GUI component) based project, but you haven't yet installed the LazDaemon package.
688684
689685Abort all loading errors, and install the LazDaemon package using the Lazarus Package Manager like described above. After Lazarus has re-compiled, the daemon project should re-load and compile without problems.
690686
691687![](/wiki-images/f/fb/Image_9.png)
692688
693689![](/wiki-images/b/b3/Image_10.png)
694690
695691### Lazarus IDE suggests to clear invalid properties from the .lpm file
696692
697693This is another issue which was observed when you try to open a TDaemon (GUI) based project, but you haven't yet installed the LazDaemon package.
698694
699695![](/wiki-images/1/13/Image_11.png)
700696
701697Abort all loading errors, and install the LazDaemon package using the Lazarus Package Manager like described above. After Lazarus has re-compiled itself, the daemon project should re-load and compile without problems.
702698
703699### The Daemon won't start on Unix because of missing threading support
704700
705701The code compiles fine, but if you try to run the daemon using a console and the -run parameter, you get a message saying something like "no thread support compiled in". If you try to start the dameon through systemctl, you won't see any message, it simply won't seem to run. You can use "systemctl status" to see the last error caused by the daemon, this will reveal the same crash infos like starting it using -run.
706702
707703``` pascal
708704This binary has no thread support compiled in.
709705Recompile the application with a thread-driver in the program uses clause before other units using thread.
710706Runtime error 232 at ...
711707
712708No heap dump by heaptrc unit
713709Exitcode = 232
714710```
715711
716712Most likely you compiled your project without support for the CThreads library (not required on Windows). See the above project lpr file sample code and the notes about "UseCThreads". The short of it is to go to the .lpr file and remove the {\$IFDEF UseCThreads} ... {\$ENDIF} around the "uses CThreads" statement, so the CThreads library gets linked into your code on Linux. On Windows this library is not required.
717713
718714### Debugging Issues observed on Windows
719715
720716The "Pause" button in the Lazarus symbol bar activates, if a breakpoint is hit, but it does not seem to work when debugging a running process remotely, debugging will hang if the button is pressed. Use "Run" \[F9\] instead to resume debugging after a breakpoint.
721717
722718To attach the debugger to the running daemon process you need to run the Lazarus IDE with Administrative Prvilege (elevated), otherwise you will get "Error 5 (access denied)" when trying to attach the debugger.
723719
724720If all debugging selections in the "Run" menu are unavailable (grayed), navigate to "Project" - "Project Options" - "Debugger" and set the "Debugger Backend" to "Gdb \[GNU debugger (gdb)\]". It has been observed that this setting may get messed up if you copy the project source files from one computer / Lazarus installation over to a different one.
725721
726722### Debugging Issues observed on Linux
727723
728724Using "Attach to program" to debug a running daemon via process ID (PID) does not seem to work, you get an error "Debugger Error" ... "Attach failed". One reason may be that you haven't specified a user in the service control file, and thus the service runs as "root", which hampers debugging. Besides of running the service using a dedicated service user account, as a workaround, consider to start debugging by loading the daemon from within Lazarus using "Run" - "Run Parameters" and entering the -run command line parameter. This way debugging does work, but note that the code runs in a different context (user instead of system- or service user account), which may change it's behaviour because of permission related issues.
729725
730726### Daemons have no Access to Network- and Cloud Drives (Onedrive, Dropbox)
731727
732728When choosing the directory for storing the daemon executable (which is by default also used for logging), keep in mind that once the daemon runs in the background it does usually run under the context of a system- or service account. User-specific virtual drives created in one user's account are usually available neither to other user accounts nor to the system account. If you run the daemon from a networked/cloud drive, it is likely that the daemon won't start, since the OS will not be able to find the executable, and that write attempts to the log will fail, since by default the log file is written where the executable is. This may be confusing, since -install and -uninstall will likely work and log fine, because they are usually executed by hand and thus run in your user's context.
733729
734730### Specifying a Service User Account does not work on Linux
735731
736732If you start the daemon and check which account it runs under, it appears to run as root, despite you have specified a different account in your systemd .service file.
737733
738734There are (unconfirmed) reports around that (on some versions of Linux?) in the .service file controlling the systemd the "User" entry must appear before the "ExecStart" entry to work properly, like shown in the code samples in the sections about Linux install and uninstall support.
739735
740736### System Codepage / UTF-8
741737
742738\[Old content, needs verfification 3/2022, may be obsolete\] A LazDeamon project is working with default, not UTF-8, codepage. The *-dDisableUTF8RTL* mode has to be activated with *Project Options ...* -\> *Compiler Options* -\> *Additions and Overrides* -\> *Use system encoding*.
743739
744740## \[Some historical contents - needs to be verified and integrated or removed\]
745741
746742\[Old content, needs verfification 3/2022, may be obsolete\]
747743
748744### Linux (only for older Debian)
749745
750746Download, configure, and "Save As" - the sample script located at Web Archive: [1](https://web.archive.org/web/20130209102726/http://aurawin.com/lazarus/debian-service.sh) (The original link is dead for a long time).
751747
752748- SVC_ALIAS is the long description of your application
753749- SVC_FILENAME is the actual file name of your compiled service application
754750- SVC_DIR is the place your you copied the service application
755751- SVC_SERVICE_SCRIPT is the final name of the service.sh when you "Save As" the customized debian-service.sh script.
756752
757753Place your script in the /etc/init.d/ folder
758754
759755start the service by running "sudo service Name_Of_Your_Script start"
760756
761757> **Note:** sudo has some variations, e.g.:
762758>
763759> ```text
764760> sudo -s #
765761> sudo -H #
766762> sudo -i #
767763> sudo su #
768764> ```
769765>
770766> \
771767> `sudo sh  #`
772768
773769In 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.
774770
775771Option 1
776772
777773``` bash
778774sudo update-rc.d Name_Of_Your_Script defaults
779775```
780776
781777Option 2
782778
783779``` bash
784780sudo apt-get install chkconfig
785781sudo chkconfig --add Name_Of_Your_Script
786782sudo chkconfig --level 2345 Name_Of_Your_Script on
787783```
788784
789785## See also
790786
791787- [GitHub Repository](https://github.com/arminlinder/Lazarus-FPC-Wiki-Code-Samples/zipball/master/) Complete demo project sample code (.zip)
792788- [[macOS daemons and agents]] - macOS native agents using launchd
793789- [[ServiceManager]] Example for the Free Pascal unit for managing Windows services
794790- [Taming the daemon: PDF by Michaël Van Canneyt](https://www.freepascal.org/~michael/articles/daemons/daemons.pdf)
795791- [[Docker Containerization]] - Containerization as a means to create daemons / services
796792- [[UniqueInstance]]
797793
798794---
799795*From the Free Pascal wiki, page "Daemons and Services", as it stood on 2022-12-29 after a change by Alextp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history