C++ - How to execute a command on application exit? - c++

I am very new to C++ and have recently started a project for which I need to access a device, collect certain data and forward it to a datastream on a local network.
While my application does all the things require it lacks on function: When I close the window, in which the application is running it does not stop the hardware-device. The result is, that I have to do a hardware reset every time I am finished with the program. This is not only inconvienient but impossible for the programms intended usage.
I basically just want to set a callback for a function, that is executed, when the program is closed (either by clicking the x, pressing Alt-F4 etc.)
Is this possible? I the possibility to create a handler for such events:
BOOL WINAPI ConsoleHandler(DWORD dwCtrlEvent)
{
switch (dwCtrlEvent)
{
case CTRL_CLOSE_EVENT:
// something
case CTRL_SHUTDOWN_EVENT:
// the same?
default:
return FALSE;
}
}
If this is a correct approach I am wondering how to use this handler? Do I need to create such a handler in my program and the update is constantly?
I am grateful for any help
Jonas

Proper RAII usage would help you in this case.
This basically says to wrap resource ownership inside of objects. You can then create an object on program start and clean any resources up on program end:
struct DeviceManager
{
DeviceManager() { InitDevice(); }
~DeviceManager() { DecativateDevice(); }
};
DeviceManager dm; //namespace scope, single translation unit
dm will be initialized on program start-up, before entry to main() and will be released on program end.

There's a standard library function atexit, which allows you register a callback to be called when the program exits normally.
To handle abnormal termination, you can employ an exception handler. Simple try{}/catch{} block with the handling code in or after the catch{} should suffice for most simple programs. For advanced setup, refer to structured exception handling here.

While you can put in special handlers for various shutdown events, you should consider designing resource control in a more object oriented way, using what is known as RAII (resource acquisition is initialization). This design pattern involves having a class whose creation initializes the underlying device and whose destructor closes and cleans up the underlying device. Thus no matter how the owner of this class is destroyed, the device will be closed.

I'd make sure that my project is split into the hardware driver, keeping the hardware in a sane state, and the user interface presenting the data to the user.
This way, when the user interface is closed, the driver continues running, cleans up and only then finishes. This also works when the UI is forcibly closed, e.g. at system shutdown, or using the task manager.
You might want to look into the UMDF for more details.

Related

C++ SetConsoleCtrlHandler, passing data for cleanup without globals

I'm trying to check when the console is closed through the close button on Windows. I read about SetConsoleCtrlHandler and I thought I'd use that, but there's some cleanup I want to do in my main function. I'll make a small example describing what I want to do for my larger program.
BOOL CtrlHandler( DWORD fdwCtrlType )
{
switch( fdwCtrlType )
{
//Cleanup exit
case CTRL_CLOSE_EVENT:
bool* programIsOn = &???; //How do I pass the address to that variable in this function?
*programIsOn = false;
return( TRUE );
default:
return FALSE;
}
}
int main(){
MyObject obj = new MyObject();
bool programIsOn = true;
//How do I pass the address of programIsOn here?
if(!SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE )){
cout << "Could not set CtrlHandler. Exiting." << endl;
return 0;
}
while(programIsOn){
//...
}
//CLEANUP HERE
delete obj;
return 0;
}
I want to perform cleanup when my program closes via the console close event, however if I just close the console the main function doesn't terminate and is forced to stop. I thought of passing in programIsOn's address to the CtrlHandler callback but I have no idea how to do this without using a global variable.
TL;DR: Proper handling of this control signal is complicated. Don't bother with any 'clean-up' unless it's absolutely necessary.
The system creates a new thread (see the Remarks) in your application, which is then used to execute the handler function you registered. That immediately causes a few issues and forces you in a particular design direction.
Namely, your program suddenly became multi-threaded, with all the complications that brings. Just setting a 'program should stop' (global) boolean variable to true in the handler is not going to work; this has to be done in a thread-aware manner.
Another complication this handler brings is that the moment it returns the program is terminated as per a call to ExitProcess. This means that the handler should wait for the program to finish, again in a thread-aware manner. Queue the next complication, where the OS gives you only 10 seconds to respond to the handler before the program is terminated anyway.
The biggest issue here, I think, is that all these issues force your program to be designed in a very particular way that potentially permeates every nook and cranny of your code.
It's not necessary for your program to clean up any handles, objects, locks or memory it uses: these will all be cleaned up by Windows when your program exits.
Therefore, your clean-up code should consists solely of those operations that need to happen and otherwise wouldn't happen, such as write the end of a log file, delete temporary files, etc.
In fact, it is recommended to not perform such clean-up, as it only slows down the closing of the application and can be so hard to get right in 'unexpected termination' cases; The Old New Thing has a wonderful post about it that's also relevant to this situation.
There are two general choices here for the way to handle the remaining clean-up:
The handler routine does all the clean-up, or
the main application does all the clean-up.
Number 1 has the issue that it's very hard to determine what clean-up to perform (as this depends on where the main program is currently executing) and it's doing so 'while the engine is still running'. Number 2 means that every piece of code in the the main application needs to be aware of the possibility of termination and have short-circuit code to handle such.
So if you truly must, necessarily, absolutely, perform some additional clean-up, choose method 2. Add a global variable, preferably a std::atomic<bool> if C++11 is available to you, and use that to track whether or not the program should exit. Have the handler set it to true
// Shared global variable to track forced termination.
std::atomic<bool> programShouldExit = false;
// In the console handler:
BOOL WINAPI CtrlHandler( DWORD fdwCtrlType )
{
...
programShouldExit = true;
Sleep(10000); // Sleep for 10 seconds; after this returns the program will be terminated if it hasn't already.
}
// In the main application, regular checks should be made:
if (programShouldExit.load())
{
// Short-circuit execution, such as return from function, throw exception, etc.
}
Where you can pick your favourite short-circuiting method, for instance throwing an exception and using the RAII pattern to guard resources.
In the console handler, we sleep for as long as we think we can get away with (it doesn't really matter); the hope is that the main thread will have exited by then causing the application to exit. If not, either the sleep ends, the handler returns and the application is closed, or the OS became impatient and killed the process.
Conclusion: Don't bother with clean-up. Even if there is something you prefer to have done, such as deleting temporary files, I'd recommend you don't. It's truly not worth the hassle (but that's my opinion). If you really must, then use thread-safe means to notify the main thread that it must exit. Modify all longer-running code to handle the exit status and all other code to handle the failure of the longer-running code. Exceptions and RAII can be used to make this more manageable, for instance.
And this is why I feel that it's a very poor design choice, born from legacy code. Just being able to handle an 'exit request' requires you to jump through hoops.

Runtime event handler in cpp?

Working on a cpp project, where I need something like runtime event handler. My primary goal is to keep a track of various events that takes place in a sample program and based on the events specific handlers are triggered.
These event triggering handlers/functions are not contributing anything to the global objective of the sample program, but are just keeping track over various events in the cpp sample program.
My question is it prossible to create soemthing like custom eventhandlers in cpp?
If yes, is there any tutorial for creating such custom eventhandler?
eg:
Event are like failed to enter while loop. successfully entered while loop, created object, deleted object, changed global variable etc.
The simplest form of event handler is a registered callback function pointer:
enum Events {
FailedEnteringWhileLoop ,
SuccessfullyEnteredWhileLoop ,
};
typedef void(EventHandler*)(Events);
void MyEventHandler(Events ev) {
switch(ev) {
case FailedEnteringWhileLoop:
// Do something
break;
case SuccessfullyEnteredWhileLoop:
// Do something
break;
}
}
EventHandler evh = MyEventHandler;
bool whileLoopEntered = false;
while(condition) {
if(!whileLoopEntered) {
whileLoopEntered = true;
(*evh)(SuccessfullyEnteredWhileLoop);
}
}
if(!whileLoopEntered) {
(*evh)(FailedEnteringWhileLoop);
}
I am looking for events like failed to enter while loop. successfully
entered while loop, created object, deleted object, changed global
variable etc.
The C++ language itself does not track these kinds of things as "events". Generally speaking it doesn't provide hooks into any of the various fundamental activities that happen across code.
So to do what you're asking for requires building an infrastructure yourself and working it into your code in various ways. (Or finding someone else who has done the same sort of work already and made it available. Although you still would have to integrate it into your code.)
To give some idea of what might have to be done:
For creating and deleting objects you can override the new and delete operators. But that doesn't cover stack/local/etc objects. Otherwise you could wedge something the constructors and destructors of every class you want to track, or even have all of them derive from a common base class which encapsulates the tracking.
For changes to a variable, you would have to wrap that variable in a container which only exposes the ability to change it through member functions. Then those could be coded to raise events.
For entering loops... You're out of luck because a loop isn't an entity that can be extended or hooked. You literally have to put some kind of call at every loop you want to track.
As for the rest of the infrastructure, you would probably end up doing something like having all of those various "events" call to some kind of global logging object. If you need different things catch different events over the course of a program, then you might also need to build a way of registering and de-registering listeners (the listeners themselves being based on an interface to derive from or std::function or whatever suits your use case).
But in the end since there isn't an out-of-the-box way provided by the language, you might want to re-consider what you really want and what you hope to achieve with it. In fact you might be better off asking your question in terms how to accomplish the end goal you wanted this for rather than how to do this "event" system.

Shutdown Hook c++

is there some way to run code on termination, no matter what kind termination (abnormal,normal,uncaught exception etc.)?
I know its actually possible in Java, but is it even possible in C++? Im assuming a windows environment.
No -- if somebody invokes TerminateProcess, your process will be destroyed without further adieu, and (in particular) without any chance to run any more code in the process of shutting down.
For normal closing applciation I would suggest
atexit()
One good way to approach the problem is using the C++ RAII idiom, which here means that cleanup operations can be placed in the destructor of an object, i.e.
class ShutdownHook {
~ShutdownHook() {
// exit handler code
}
};
int main() {
ShutdownHook h;
//...
}
See the Object Lifetime Manager in ACE library. At the linked document, they discuss about the atexit function as well.
Not for any kind of termination; there are signals that are designed to not be handled, like KILL on Linux.
These signals are designed to terminate a program that has consumed all memory, or CPU, or some other resources, and has left the computer in a state that makes it difficult to run a handler function.

Design a transmitter class in C++: buffer data from server & send to client

I'm writing a class "Tmt" that acts between a server and clients through sockets. My Tmt class will receive data from server, build up a queue internally and perform some operation on the data in the queue before they are available to the client.
I have already setup the socket connection and I can call
receiverData(); // to get data from server
The client will use my class Tmt as follows:
Tmt mytmt=new Tmt();
mymt.getProcessedData(); //to get one frame.
My question is how to let the Tmt class keep receiving data from server in the background once it is created and add them to the queue. I have some experience in multi-thread in C, but I'm not sure how this "working in the background" concept will be implemented in a class in C++. Please advice, thanks!
One option would be to associate a thread with each instance of the class (perhaps by creating a thread in the constructor). This thread continuously reads data from the network and adds the data to the queue as it becomes available. If the thread is marked private (i.e. class clients aren't aware of its existence), then it will essentially be running "in the background" with no explicit intervention. It would be up to the Tmt object to manage its state.
As for actual thread implementations in C++, you can just use Good ol' Pthreads in C++ just fine. However, a much better approach would probably be to use the Boost threading library, which encapsulates all the thread state into its own class. They also offer a whole bunch of synchronization primitives that are just like the pthread versions, but substantially easier to use.
Hope this helps!
By the way - I'd recommend just naming the class Transmit. No reason to be overly terse. ;-)
IMHO, multithreading is not the best solution for this kind of classes.
Introducing background threads can cause many problems, you must devise guards against multiple unnecessary thread creation at the least. Also threads need apparent initialize and cleanup. For instance, usual thread cleanup include thread join operation (wait for thread to stop) that could cause deadlocks, resource leaks, irresponsible UIs, etc.
Single thread asynchronous socket communication could be more appropriate to this scenario.
Let me draw sample code about this:
class Tmt {
...
public:
...
bool doProcessing()
{
receiverData();
// process data
// return true if data available
}
T getProcessedData()
{
// return processed data
}
}
Tmt class users must run loop doing doProcessing, getProcessedData call.
Tmt myTmt;
...
while (needMoreData)
{
if (myTmt.doProcessing())
{
myTmt.getProcessedData();
...
}
}
If Tmt users want background processing they can easily create another thread and doing Tmt job in there. This time, thread management works are covered by Tmt users.
If Tmt users prefer single thread approach they can do it without any problem.
Also noted that famous curl library uses this kind of design.

Basic signal handling in C++

This is a pretty basic scenario but I'm not finding too many helpful resources. I have a C++ program running in Linux that does file processing. Reads lines, does various transformations, writes data into a database. There's certain variables (stored in the database) that affect the processing which I'm currently reading at every iteration because I want processing to be as up to date as possible, but a slight lag is OK. But those variables change pretty rarely, and the reads are expensive over time (10 million plus rows a day). I could space out the reads to every n iterations or simply restart the program when a variable changes, but those seem hackish.
What I would like to do instead is have the program trigger a reread of the variables when it receives a SIGHUP. Everything I'm reading about signal handling is talking about the C signal library which I'm not sure how to tie in to my program's classes. The Boost signal libraries seem to be more about inter-object communication rather than handling OS signals.
Can anybody help? It seems like this should be incredibly simple, but I'm pretty rusty with C++.
I would handle it just like you might handle it in C. I think it's perfectly fine to have a stand-alone signal handler function, since you'll just be posting to a semaphore or setting a variable or some such, which another thread or object can inspect to determine if it needs to re-read the settings.
#include <signal.h>
#include <stdio.h>
/* or you might use a semaphore to notify a waiting thread */
static volatile sig_atomic_t sig_caught = 0;
void handle_sighup(int signum)
{
/* in case we registered this handler for multiple signals */
if (signum == SIGHUP) {
sig_caught = 1;
}
}
int main(int argc, char* argv[])
{
/* you may also prefer sigaction() instead of signal() */
signal(SIGHUP, handle_sighup);
while(1) {
if (sig_caught) {
sig_caught = 0;
printf("caught a SIGHUP. I should re-read settings.\n");
}
}
return 0;
}
You can test sending a SIGHUP by using kill -1 `pidof yourapp`.
I'd recommend checking out this link which gives the details on registering a signal.
Unless I'm mistaken, one important thing to remember is that any function inside an object expects a referent parameter, which means non-static member functions can't be signal handlers. I believe you'll need to register it either to a static member function, or some kind of global function. From there, if you have a specific object function you want to take care of your update, you'll need a way to reference that object.
There are several possibilities; it would not necessarily be overkill to implement all of them:
Respond to a specific signal, just like C does. C++ works the same way. See the documentation for signal().
Trigger on the modification timestamp of some file changing, like the database if it is stored in a flat file.
Trigger once per hour, or once per day (whatever makes sense).
You can define a Boost signal corresponding to the OS signal and tie the Boost signal to your slot to invoke the respective handler.