Shutdown and Powerdown

Overview

edit

Here we look at at how you can do what ever is necessary when your app closes down. This is a particular issue when the end user powers down their computer while your app is still running.

While Windows and MacOS apps do have reliable graceful powerdown models, not all Linux combinations of Desktops and widgets sets do. In particular, Gnome Desktops will probably deny your app a chance to do that clean up or save. On platforms other than Gnome, Qt5 or Qt6 apps are a better choice and how to implement that is detailed below.

If your application has some state information it needs to save, remote connections to drop or similar, there are a number of different scenarios you might need to consider -

  • User initiated close, perhaps with the Window Decoration close button or something your app detects, a menu choice, a button or special key combination. Such GUI apps may call TForm.Close and are directed to FormCloseQuery() which can be closed to do what is needed and then allows the close down to proceed. Thats all we'll say here about this action.
  • The application getting a SigHUP, SigINT or TERM (but NOT at powerdown). This might be triggered by the user (or a SysAdmin) using the kill command on Unix, the Task manager on Windows or other "process Management tools. FPC/Lazarus applications respond immediately to such signals, GUI apps do not call OnCloseQuery unless you code it in. You need to provide your own signal handler method, divert the signals to it and ensure it does what you want.
  • A PowerDown (or restart) event while the application is still running. To get time to do whatever is needed requires a different approach. FPC command line apps can use signal handling techniques like above but GUI/Lazarus apps must use tools provided in TApplication. In particular, Application.OnQueryEndSession.

Its important to note that these are three different processes, while your code can link them together, it does not happen by default.

What is not addressed here is a user logging out (as opposed to power down or restart) of a linux session (with an LCL app still running). Apparently, TApplication.OnQueryEndSession does not detect this situation, to be confirmed.

Problems on Linux

edit

This table is an attempt to describe linux combinations that allow you to do that clean up or save at powerdown. Its is in particular about responding correctly to OnQueryEndSession (Qt5 Q6) but also looks at using Signal Handlers for gtk2 and maybe gtk3.

Tests gtk2 gtk3 Qt5 Qt6 - Notes -
Trixie KDE W No yes yes yes The recent KDE / Wayland combinations that do work do NOT call QueryEndSession but jump direct to FormCloseQuery when Powerdown happens. I guess thats OK.
Trixie KDE W Yes Yes Yes Using the Signal Handler model, see note 1.
Trixie KDE No No yes No Using XOrg instead of wayland. 5-7 sec delay with gtk2, gtk3 and Qt5 (but only Qt5 does ctrl powerdown)
Trixie Gnome W No No No No
Trixie Gnome Xorg No No Yes Yes
Trixie XFCE No No Yes Yes
Trixie XFCE Yes Using the Signal Handler model, see note 1.
U2404 Mate No No Yes n.a.
U2404 Mate Part Yes Using the Signal Handler model, see note 1.
U2510 Gnome No No No No Cannot switch to XOrg
Fedora41 KDE No Yes Yes Yes The recent KDE / Wayland combinations that do work do NOT call QueryEndSession but jump direct to FormCloseQuery when Powerdown happens. I guess thats OK.
Fedora41 KDE Yes Using the Signal Handler model, see note 1.
Mint 22.1 Cin No No Yes n.a.
Mint 22.1 Cin No Yes Using the Signal Handler model, see note 1. Almost works but OS does not allow enough time ?
Endeavour Mate No No Yes Yes A current Arch

Note 1 gtk2 and some times gtk3 will do a graceful powerdown using the Signal Handler model. Seems a reliable workaround and is documented further down this page under Signal Handler. Probably makes sense on all Linux builds.

Strategy

edit
  • Advise your end users to not use Gnome Desktop, they will not get a chance to save anything at Powerdown with Gnome.
  • Use both the Signal Handling and OnQuerySessionEnd in your Linux apps.
  • Perhaps advise your end users you cannot guarantee everything is saved unless they close the app, themselves, before powerdown the computer.

Signal Handlers

edit

Linux (possibly MacOS), to confirm ?

edit

This is typically used to handle signals like SigTERM, SigINT and SigHUP sent from, eg, kill command. It does not come into play during a PowerDown event for LCL apps (except perhaps gtk2 ?). A signal handler may look a bit like this -

procedure HandleSigTERM(aSignal: LongInt); cdecl;
begin
    if SignalReceived = 0 then begin
        SignalReceived := aSignal;
        MainForm.Close;
    end;
end;

Here, SignalReceived is a global, and is used to ensure only one shutdown signal is acted on. Its may also be used elsewhere to determine what signal triggered the change. Maybe you don't even want a full shutdown on every signal ? The call to MainForm.Close needs to be replaced with something more suitable in a CLI application of course.

Then, somewhere early on in the application's life we divert the signal to our handler. This might be in the main procedure of a CLI application or, perhaps in the main form FormCreate method

...
FpSignal(SigTERM, @HandleSigTERM); 
FpSignal(SigHUP, @HandleSigTERM);
....

You should consider handling SigTERM, SigHUP, SigINT (ie Ctrl+C) and any signals you may see for your own purposes. Send them all to the same handler if you like or setup a separate handler for each. You cannot redirect SigKILL or SigSTOP.

Windows

edit

Windows applications can be killed from the task manager, seems you get a bit more than a second to do so. Thats not good at all. Hopefully, someone with more Windows skills than this author will contribute ?

Power Down Events

edit

While command line apps and gtk2 apps works nicely with the Signal Handler model, LCL, Lazarus GUI apps do not work at Power Down. Fortunately, LCL provides an easy solution, Application.OnQueryEndSession and Application.OnEndSession. Either of these two properties of TApplication can be assigned an event handler that, in a simple case, calls (TForm.)close. You have the time to clean up, save, disconnect etc and, as the handler exits, the shutdown proceeds. With Linux, there seems no limit on how long you take to do these jobs. So, be very careful you app does not get a reputation for preventing the host computer from shutting down ! With Windows, after, maybe, 5 seconds, a dialog pops up asking if you want to kill the delaying app. Again, seems you can wait for an unspecified time.

The OnQueryEndSession event happens first, then OnEndSession after the OnQueryEndSession handler has returned. OnQueryEndSession appears to be able to cancel the shutdown, would seem a strange thing to do during a PowerDown.

uses .... {$ifdef UNIX}BaseUnix{$endif} 

procedure TMainForm.QueryEndSession(var cancel:Boolean);
begin
    CloseOpenStuff('QES');
    Cancel := False;
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
    ...
    Application.OnQueryEndSession := @QueryEndSession;       // Thats to handle a PowerDown situation
    {$ifdef UNIX}
    FpSignal(SigTERM, @HandleSigTERM);                       // Thats to handle SigTERM from, eg the kill command
    FpSignal(SigHUP, @HandleSigTERM);                        // HUP, as above
    {$endif}
end;

In this case we are using OnQueryEndSession, so set Cancel to be false, probably not necessary but lets be sure. The handler, QueryEndSession, calls a method CloseOpenStuff (not shown) that does whatever is necessary, it returns, and then the handler returns and the shutdown can proceed.

The form's OnCloseQuery and OnClose will still be called but should have nothing to do. In this mode, on Linux at least, they are not allowed time to do much at all. So, make sure you do your clean up in OnQueryEndSession and make sure TForm.OnCloseQuery can tell its all been done.

In the above example, we have also included (Unix only) the redirection to a signal handler (not shown) to handle SigTERM and SigHUP, they are not useful at powerdown but ensure a graceful exit if the app is forced to close at any other time.