Shutdown Hook c++ - 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.

Related

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

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.

Does the process automatically clean up the resources taken by pthreads upon exit

Assume that I have a code something like this :
void *my_thread(void *data)
{
while (1) { }
}
void foo_init(struct my_resource *res)
{
pthread_create(&res->tid, NULL, my_thread, res);
/* Some init code */
}
void foo_exit(void)
{
/* Some exit code */
}
The scenario is something like this. When the process gets initialized, the function foo_init() is called with a pointer to my allocated resources(the allocation is done automatically by some other function, which isn't under my control). Within the function I am creating a pthread, which runs in infinite loop.
After a while when the process is about to terminate, the function foo_exit() is called, but this time without the pointer to my resources, and hence I am unable to call pthread_join(), as my tid is contained within my_resource structure.
Now my question is that, whether the resources pertaining to the pthreads are destroyed upon the termination of the process by the OS or not? If yes, how can I make that sure.
Also is it safe to terminate the process without calling pthread_join()?
Thanks in advance.
If you're talking about allocated memory, yes. When a process exits all virtual memory pages allocated to that process are returned to the system, which will clean up all memory allocated within your process.
Generally the OS is supposed to clean up all resources associated with a process on exit. It will handle closing file handles (which can include sockets and RPC mechanisms), wiping away the stack, and cleaning up kernel resources for the task.
Short answer, if the OS doesn't clean up after a process it is a bug in the OS. But none of us write buggy software right?
All "regular" resources needed by a process are released automatically by the OS when the process terminates (e.g. memory, sockets, file handles). The most important exception is shared memory but also other resources can be problematic if they're managed not by OS but by other processes.
For example if your process talks to a daemon or to another process like a window manager and allocates resources, whether or not those are released in case the process terminates without releasing them depends on the implementation.
I think the question can be answered another way: pthreads do not own any resources, resources are owned by the process. (A pthread may be the "custodian" of resources, such as memory it has malloc'ed, but it is not the owner.) When the process terminates, any still running pthreads suddenly stop and then the usual process clean-up happens.
POSIX says (for _Exit()):
• Threads terminated by a call to _Exit() or _exit() shall not invoke their cancellation cleanup handlers or per-thread data destructors.
For exit() POSIX specifies a little more clean-up -- in particular running all atexit() things and flushing streams and such -- before proceeding as if by _Exit(). Note that this does not invoke any pthread cancellation cleanup for any pthread -- the system cannot tell what state any pthread is in, and cannot be sure of being able to pthread_cancel() all pthreads, so does the only thing it can do, which is to stop them all dead.
I can recommend the Single UNIX® Specification (POSIX) -- like any standard, it's not an easy read, but worth getting to know.

cancel a c++ 11 async task

How can I stop/cancel an asynchronous task created with std::async and policy std::launch::async? In other words, I have started a task running on another thread, using future object. Is there a way to cancel or stop the running task?
In short no.
Longer explanation: There is no safe way to cancel any threads in standard C++. This would require thread cancellation. This feature has been discussed many times during the C++11 standardisation and the general consensus is that there is no safe way to do so. To my knowledge there were three main considered ways to do thread cancellation in C++.
Abort the thread. This would be rather like an emergency stop. Unfortunately it would result in no stack unwinding or destructors called. The thread could have been in any state so possibly holding mutexes, having heap allocated data which would be leaked, etc. This was clearly never going to be considered for long since it would make the entire program undefined. If you want to do this yourself however just use native_handle to do it. It will however be non-portable.
Compulsory cancellation/interruption points. When a thread cancel is requested it internally sets some variable so that next time any of a predefined set of interruption points is called (such as sleep, wait, etc) it will throw some exception. This would cause the stack to unwind and cleanup can be done. Unfortunately this type of system makes it very difficult make any code exception safe since most multithreaded code can then suddenly throw. This is the model that boost.thread uses. It uses disable_interruption to work around some of the problems but it is still exceedingly difficult to get right for anything but the simplest of cases. Boost.thread uses this model but it has always been considered risky and understandably it was not accepted into the standard along with the rest.
Voluntary cancellation/interruption points. ultimately this boils down to checking some condition yourself when you want to and if appropriate exiting the thread yourself in a controlled fashion. I vaguely recall some talk about adding some library features to help with this but it was never agreed upon.
I would just use a variation of 3. If you are using lambdas for instance it would be quite easy to reference an atomic "cancel" variable which you can check from time to time.
In C++11 (I think) there is no standard way to cancel a thread. If you get std::thread::native_handle(), you can do something with it but that's not portable.
maybe you can do like this way by checking some condition:
class Timer{
public:
Timer():timer_destory(false){}
~Timer(){
timer_destory=true;
for(auto result:async_result){
result.get();
}
}
int register_event(){
async_result.push_back(
std::async(std::launch::async,[](std::atomic<bool>& timer_destory){
while(!timer_destory){
//do something
}
},std::ref(timer_destory))
);
}
private:
std::vector<std::future<int>> async_result;
std::atomic<bool> timer_destory;
}

Can I interrupt function if it is executed for too long?

I a have third party function which I use in my program. I can't replace it; it's in a dynamic library, so I also can't edit it. The problem is that it sometimes runs for too long.
So, can I do anything to stop this function from running if it runs more than 10 seconds for example? (It's OK to close program in this scenario.)
PS. I have Linux, and this program won't have to be ported anywhere else.
What I want is something like this:
#include <stdio.h>
#include <stdlib.h>
void func1 (void) // I can not change contents of this.
{
int i; // random
while (i % 2 == 0);
}
int main ()
{
setTryTime(10000);
timeTry{
func1();
} catchTime {
puts("function executed too long, aborting..");
}
return 0;
}
Sure. And you'd do it just the way you suggested in your title: "signals".
Specifically, an "alarm" signal:
http://linux.die.net/man/2/alarm
http://beej.us/guide/bgipc/output/html/multipage/signals.html
If you really have to do this, you probably want to spawn a process that does nothing but invoke the function and return its result to the caller. If it runs too long, you can kill that process.
By putting it into its own process, you stand a decent (not great, but decent) chance of cleaning up at least most of what it was doing so when it dies unexpectedly it probably won't make a complete mess of things that will lead to later problem.
The potential problem with forcefully cancelling a running function is that it may "own" resources that it intended to return later. The kind of resources that can be problems include:
heap memory allocations (free store)
shared memory segments
threads
sockets
file handles
locks
Some of these resources are managed on a per-process basis, so letting the function run in a different process (perhaps using fork) makes it easier to kill cleanly. Other resources can outlive a process, and really must be cleaned up explicitly. Depending on your operating system, it's also possible that the function may be part-way through interacting with some hardware driver or device, and killing it unexpectedly may leave that driver or device in a bizarre state such that it won't work until after a restart.
If you happen to know that the function doesn't use any of these kind of resources, then you can kill it confidently. But, it's hard to guarantee that: in a large system with many such decisions - which the compiler can't check - evolution of code in functions like func1() is likely to introduce dependencies on such resources.
If you must do this, I'd suggest running it in a different process or thread, and using kill() for processes, pthread_kill if func1() has some support for terminating when a flag is set asynchronously, or the non-portable pthread_cancel if there's really no other choice.

How to insulate a job/thread from crashes

I'm working on a library where I'm farming various tasks out to some third-party libraries that do some relatively sketchy or dangerous platform-specific work. (In specific, I'm writing a mathematical function parser that calls JIT-compilers, like LLVM or libjit, to build machine code.) In practice, these third-party libraries have a tendency to be crashy (part of this is my fault, of course, but I still want some insurance).
I'd like, then, to be able to very gracefully deal with a job dying horribly -- SIGSEGV, SIGILL, etc. -- without bringing down the rest of my code (or the code of the users calling my library functions). To be clear, I don't care if that particular job can continue (I'm not going to try to repair a crash condition), nor do I really care about the state of the objects after such a crash (I'll discard them immediately if there's a crash). I just want to be able to detect that a crash has occurred, stop the crash from taking out the entire process, stop calling whatever's crashing, and resume execution.
(For a little more context, the code at the moment is a for loop, testing each of the available JIT-compilers. Some of these compilers might crash. If they do, I just want to execute continue; and get on with testing another compiler.)
Currently, I've got a signal()-based implementation that fails pretty horribly; of course, it's undefined behavior to longjmp() out of a signal handler, and signal handlers are pretty much expected to end with exit() or terminate(). Just throwing the code in another thread doesn't help by itself, at least the way I've tested it so far. I also can't hack out a way to make this work using C++ exceptions.
So, what's the best way to insulate a particular set of instructions / thread / job from crashes?
Spawn a new process.
What output do you collect when a job succeeds?
I ask because if the output is low bandwidth I would be tempted to run each job in its own process.
Each of these crashy jobs you fire up has a high chance of corrupting memory used elsewhere in your process.
Processes offer the best protection.
Processes offer the best protection, but it's possible you can't do that.
If your threads' entry points are functions you wrote, (for example, ThreadProc in the Windows world), then you can wrap them in try{...}catch(...) blocks. If you want to communicate that an exception has occurred, then you can communicate specific error codes back to the main thread or use some other mechanism. If you want to log not only that an exception has occured but what that exception was, then you'll need to catch specific exception types and extract diagnostic information from them to communicate back to the main thread. A'la:
int my_tempermental_thread()
{
try
{
// ... magic happens ...
return 0;
}
catch( const std::exception& ex )
{
// ... or maybe it doesn't ...
string reason = ex.what();
tell_main_thread_what_went_wong(reason);
return 1;
}
catch( ... )
{
// ... definitely not magical happenings here ...
tell_main_thread_what_went_wrong("uh, something bad and undefined");
return 2;
}
}
Be aware that if you go this way you run the risk of hosing the host process when the exceptions do occur. You say you're not trying to correct the problem, but how do you know the malignant thread didn't eat your stack for example? Catch-and-ignore is a great way to create horribly confounding bugs.
On Windows, you might be able to use VirtualProtect(YourMemory, PAGE_READONLY) when calling the untrusted code. Any attempt to modify this memory would cause a Structured Exception. You can safely catch this and continue execution. However, memory allocated by that library will of course leak, as will other resources. The Linux equivalent is mprotect(YorMemory, PROT_READ), which causes a SEGV.