Windows: how to perform cleanup actions when the console window closes

Hello all, I have a console (command-line) Haskell application that communicates with some hardware equipment. The equipment needs to be initialized when my program starts, and needs to be cleanly shut down when the program ends. This is the basic structure of the program: main = readAvailableEquipment >>= \descs -> withEquipment descs $ \availableEquipment -> <<< more initialization then an infinite loop as a sockets-based server, communicating with the hardware via availableEquipment >>> withEquipment is defined as withEquipment descs action = bracket (initializeEquipment descs) closeEquipment action Basically I want closeEquipment to be executed when the program shuts down. The program is stopped by the user closing the console window (hitting the upper right 'X' in the Windows title bar). I would expect that the 'closeEquipment' action is performed since it is in the cleanup part of the 'bracket', but my testing suggests that these actions never execute. Incidentally, stopping the program via Ctrl-C doesn't work. I have tested this with GHC 8.2.2 installed via Stack (LTS 11.3). This is on Windows 10. Summary question and TLDR: how do I reliably perform cleanup actions in a Windows console program that is closed by the user by clicking the 'X' symbol in the window title bar? Thanks! Peter

Am 06.04.2018 um 10:09 schrieb Peter Dedecker:
Summary question and TLDR: how do I reliably perform cleanup actions in a Windows console program that is closed by the user by clicking the 'X' symbol in the window title bar?
You need to intercept the various events that may cause a console windows to be closed; this is done via the Windows API call SetConsoleCtrlHandler . https://stackoverflow.com/a/30843219/6944068 gives an overview, API doc is at https://docs.microsoft.com/en-us/windows/console/setconsolectrlhandler (you want to register a HandlerRoutine). The default handler simply calls ExitProcess, bypassing all shutdown activity of the runtime. That's why C++ guys complain that destructors are not called. I don't know how to register a Haskell function as a Windows callback, that will have to be answered by somebody else. HTH Jo
participants (2)
-
Joachim Durchholz
-
Peter Dedecker