Make Control-C behave like uncaught exception - c++

Is there a way to make Control-C act like an exception was thrown. i.e. basically the program exits, but on the way up all the destructors are called?

Well, you need a signal handler catch SIGINT (SIGTERM, HUP why not as well?). You don't want to use threads for something simple like this, so use the standard "self-pipe trick": write a byte (the signal value) to one end of a socketpair in your signal handler, and your main loop (there's always a select loop in there somewhere) will asynchronously read the value back. It's at that point you throw, run away, follow ordinary quit procedure, do whatever you like. Everything gets unwound and destructed just as if you were quitting for any other reason in your main application loop.

This is generally impossible or hard to do. I believe that on some systems, like GNU/Linux, you could do that if you supplied -fnon-call-exceptions -fasynchronous-unwind-tables flags to GCC (untested).
Other than the above, you have basically two options:
Either you set some sort of flag in your signal handler that you will check somewhere else to see if SIGINT has been delivered. This is useful for both *NIX and Windows platforms.
On *NIX, if you are using threads in your application already, you can handle SIGINT using, e.g., sigwait() in a separate thread as a synchronous event and force your whole application to terminate orderly.
I would suggest using the 2nd option as that is usable as general approach to the problem on Windows as well. Windows inject a thread into application that execute a user supplied handle for Ctrl-C or Ctrl-Break. If you use the 2nd option, your application will be IMHO more portable.

Related

How to safely terminate a multithreaded process

I am working on a project where we have used pthread_create to create several child threads.
The thread creation logic is not in my control as its implemented by some other part of project.
Each thread perform some operation which takes more than 30 seconds to complete.
Under normal condition the program works perfectly fine.
But the problem occurs at the time of termination of the program.
I need to exit from main as quickly as possible when I receive the SIGINT signal.
When I call exit() or return from main, the exit handlers and global objects' destructors are called. And I believe these operations are having a race condition with the running threads. And I believe there are many race conditions, which is making hard to solve all of theses.
The way I see it there are two solutions.
call _exit() and forget all de-allocation of resources
When SIGINT is there, close/kill all threads and then call exit() from main thread, which will release resources.
I think 1st option will work, but I do not want to abruptly terminate the process.
So I want to know if it is possible to terminate all child threads as quickly as possible so that exit handler & destructor can perform required clean-up task and terminate the program.
I have gone through this post, let me know if you know other ways: POSIX API call to list all the pthreads running in a process
Also, let me know if there is any other solution to this problem
What is it that you need to do before the program quits? If the answer is 'deallocate resources', then you don't need to worry. If you call _exit then the program will exit immediately and the OS will clean up everything for you.
Be aware also that what you can safely do in a signal hander is extremely limited, so attempting to perform any cleanup yourself is not recommended. If you're interested, there's a list of what you can do here. But you can't flush a file to disk, for example (which is about the only thing I can think of that you might legitimately want to do here). That's off limits.
I need to exit from main as quickly as possible when I receive the SIGINT signal.
How is that defined? Because there's no way to "exit quickly as possible" when you receive one signal like that.
You can either set flag(s), post to semaphore(s), or similar to set a state that tells other threads it's time to shut down, or you can kill the entire process.
If you elect to set flag(s) or similar to tell the other threads to shut down, you set those flags and return from your signal handler and hope the threads behave and the process shuts down cleanly.
If you elect to kill threads, there's effectively no difference in killing a thread, killing the process, or calling _exit(). You might as well just keep it simple and call _exit().
That's all you can chose between when you have to make your decision in a single signal handler call. Pick one.
A better solution is to use escalating signals. For example, when you get SIGQUIT or SIGINT, you set flag(s) or otherwise tell threads it's time to clean up and exit the process - or else. Then, say five seconds later whatever is shutting down your process sends SIGTERM and the "or else" happens. When you get SIGTERM, your signal handler simply calls _exit() - those threads had their chance and they messed it up and that's their fault. Or you can call abort() to generate a core file and maybe provide enough evidence to fix the miscreant threads that won't shut down.
And finally, five seconds later the managing process will nuke the process from orbit with SIGKILL just to be sure.

Is there a single catch-all-failures hook in c++?

I want that when and if the program will fail than it will be caught at this handler in order to do some guard notifications.
Is there a bottom handler or list of handlers that I need to register in order to be sure that a program cannot crash without passing through my handler?
Running on ubuntu and solution needed only to ubuntu
I need all kind of failure like exception memory allocation ...
The simple answer is that there is no single point where you can handle all errors in the program. You can add a try/catch (...) at in main to handle exceptions that occur after main is entered and before it completes. You can also add a handler for terminate in C++. Then depending on the OS you will also need to handle other situations differently (invalid memory references can be handled in unix/linux by handling SIG_SEGV, but that will not work in Windows --AFAIK; some other errors might trigger different signals that could or not be handled...) Further than that, there might be errors that still get unnoticed (say an invalid memory access that happens to hit a valid memory address... the program will be incorrect, but the error might go undetected)
C++ does not run in a virtual sandbox, thus there is nothing built-in to the language to catch this. You can certainly build one yourself (for example using exceptions), but it's up to your code to construct this from the foundation up.
The platform you're running on may have something you can use though. For example in Windows there is SetUnhandledExceptionFilter.
Of course all of this still depends on what it means to "crash".
On process startup, call fork. Use the parent to monitor the child. If it encounters a fatal error, the process will go away. You can detect this and do whatever you need to do when that happens. If the child wishes to terminate normally, it can simply kill its parent before terminating.
For a normal program exit you can register a handler with std::atexit().
For a program exit because of uncaught exceptions/... you can register a handler with std::set_terminate. If by "exception memory allocation" you mean a std::bad_alloc exception, than this handler should be triggered.
In Linux You need to respond to SIGABRT Signal. Your callback will be called whenever your app gets SIGABRT signal
signal(SIGABRT, &callback);
There are different Signals for different Scenarios such as SIGSEGV, SIGBUS that you ned to hook. you better hook them in different callbacks and check which error goes into what. because one error might come due to multiple problems.
No. If the process is killed with a SIGKILL, for example, no handler will be run.
P.S. FYI, this has nothing to do with the SPOF.
You can put a try/catch(...) block at the top level to catch all exceptions. But there are other ways for the program to be terminated and the ways of catching these aren't portable. On Unix-based systems you'll have to create signal handlers but even those won't stop kill -9.

How can I write cross platform c++ that handles signals?

This question is more for my personal curiosity than anything important. I'm trying to keep all my code compatible with at least Windows and Mac. So far I've learned that I should base my code on POSIX and that's just great but...
Windows doesn't have a sigaction function so signal is used? According to:
What is the difference between sigaction and signal? there are some problems with signal.
The signal() function does not block other signals from arriving while the current handler is executing; sigaction() can block other signals until the current handler returns.
The signal() function resets the signal action back to SIG_DFL (default) for almost all signals. This means that the signal() handler must reinstall itself as its first action. It also opens up a window of vulnerability between the time when the signal is detected and the handler is reinstalled during which if a second instance of the signal arrives, the default behaviour (usually terminate, sometimes with prejudice - aka core dump) occurs.
If two SIGINT's come quickly then the application will terminate with default behavior. Is there any way to fix this behavior? What other implications do these two issues have on a process that, for instance wants to block SIGINT? Are there any other issues that I'm likely to run across while using signal? How do I fix them?
You really don't want to deal with signal()'s at all.
You want "events".
Ideally, you'll find a framework that's portable to all the main environments you wish to target - that would determine your choice of "event" implementation.
Here's an interesting thread that might help:
Game Objects Talking To Each Other
PS:
The main difference between signal() and sigaction() is that sigaction() is "signal()" on steroids - more options, allows SA_RESTART, etc. I'd discourage using either one unless you really, really need to.

Function guaranteed to be called in C++ during abrupt termination or exit

What function in C++ is guaranteed to be called during abrupt termination or exit which can perform the clean up activity ..
Depending on what you mean by "abrupt termination" there are several different options:
Global destructors will be called upon normal termination (return from main, or call to exit()).
atexit() registers a function to be called on normal termination.
std::set_terminate registers a function that will be called when an exception is thrown but not caught, or when "exception handling has to be terminated for some other reason".
sigaction() registers functions to be called when your program receives signals, many of which will normally abruptly terminate your program. Signal handlers may be called when the program is in an internally-inconsistent state, and therefore are extremely limited in what they can do. For instance, they cannot do anything that might allocate memory. Also, this API is not available on Windows; there are equivalents but I am not familiar with them.
Note that all operating systems in common use provide at least one way to abruptly terminate your program that cannot be intercepted from your code. For instance, Unix has signal 9 (SIGKILL) which you can't register a handler for. This is a feature, not a bug. You, the user, need a way to make a process go away even if it has done everything in its power to make itself indestructible. Furthermore, no code can protect your process when the user's pet rabbit gnaws through the power cord on the computer. Because of this, it might be a better use of your time to design your program to recover from crashes cleanly, rather than trying to clean up when a crash happens. See this article on "crash-only design" for more about that.
Read about atexit here. However it will not be called in all cases (for example, calling abort will not trigger the function you registered with atexit).
You can implement your own signal handler, then all the signals will pass there and you can do whatever for each of them.
You are looking for set_terminate().
http://www.cplusplus.com/reference/std/exception/set_terminate/
There are other similar function in the same header, that are usable for complementary scenarios.
int main()
{
try
{
// all your code here
}
catch(...)
{
// cleanup
}
return 0;
}
What environment you're working in? by abrupt do you mean Ctrl+C or kill -9 signal?
On unix/linux you can mask some signals and provide handlers, but as far as I am aware, you cannot mask all signal (9 is an example of a signal that can't be masked, and it'll kill your process abruptly)
Some even lower level overriding on OS operation could be available, but I'm not familiar with that.
I am not an expert and I just know some few things about C++, but I know you can create handles in Unix and C in order to detect a concrete signal and then, execute a function and later, terminate the program by "exit(n)" for example.
You can do it using signal or sigaction, but the problem is that you only can use this method for any signal except SIGKILL or SIGSTOP.
Are you familiar with signal handling? I would recommend that you study that first and then come back with questions regarding it. It looks like a couple people have already alluded to it, but here is a good resource to check:
http://www.gnu.org/s/hello/manual/libc/Signal-Handling.html
Writing your own signal handlers will allow you to determine what you want to do when a particular signal is caught. As stated, there are some that can't be overridden, and for good reason. You don't want to let someone override kill -9 simply because a program that's impossible to kill could be created. However, a straight kill signal or something such as ctrl-c, ctrl-d, etc, can be caught and handled in the way of your choosing.
There is no function that captures all scenarios and works on all platfroms. If you need something for Windows you will have to handle SEH(Structured exception handling) as well. You will have to define and set handlers for various scenarios(SEH, C++ Exceptions, SIGABRT, Terminate etc.) that execute common cleanup code and. Check zack's response here for handling SIGABRT signals.
For SEH you can add a SE converter to handle SE excpetions and convert them to C++ exceptions, look at _set_se_translator for more information about how to handle SEH exceptions.
You can refer to this documentation for set_terminate handler and this is a good reference for set_unexpected.
You will have to write your own handler that will be called for every scenario.
In the end I would reccomend using some existing libraries for this purpose, I like crashrprt.

Cross-thread exception throwing

I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is to shut the application down and restart, potentially losing their work. I'd like to add some means where the user, when he realizes that his code is in an infinite loop, can hit a special key, like F10 or something, and the code will break out of the loop. But I'd like to do it without implementing a ton of checks within the script runtime. Optimally, I'd like to have a separate "debugger" thread that's mostly idle, but as one of its tasks it listens for that F10 key, and when it gets the F10 key, it will cause the script runtime thread to throw an exception, so that it will stop executing the script. So my question is, is there a way to have one thread cause another thread to throw an exception? My application is written in C++.
If the script is actually interpreted by your application then you can just tell the interpreter to stop executing whenever some user event occurs.
It's possible. Detect the keystroke in a separate thread, a hidden window and WM_HOTKEY for example. Call SuspendThread() to freeze the interpreter thread. Now use GetThreadContext() to get the CPU registers of the interpreter thread. Modify CONTEXT.Eip to the address of a function and call SetThreadContext(). Have that function call RaiseException() or throw a C++ exception. ResumeThread() and boom.
A short answer - no.
If your application runs on Windows, maybe you can send a message from this "debugger" tread and have a message loop in the main one?
The problem with that solution is, to do a message sending implementation, I'd have to set up a "listener" as part of the script interpreter. Right now, the interpreter just executes the function. The message loop is implemented outside of the interpreter. If within the function there is an infinite loop, then to break out of that script, I'd have to check for a message in between execution of each instruction in the interpreter, i.e. while(more instructions){check F10, execute script instruction}. That seems like a lot of extra unneeded checks that can slow down the script execution. But if that's the only solution, then I guess that's what it has to be. I still think there's got to be a better way. Maybe the script interpreter needs to be run on a child thread, while the main thread continues its message loop, and will then kill the script interpreter thread when it gets an F10.
Whether you code it explicitly or not, you will need to check a "interrupt" variable in the message loop. If you implement this by a simple volatile int, you will have both a very simple test and very little overhead.
It is unsafe to terminate a thread, as it is probably using resources shared across the entire process.
It is less unsafe to terminate an entire process, but that's not going to help you.
A more safe way to deal with this would be to have the interpreter check for events on a regular basis and treat the stop event as a case to terminate (or at least spill out to a higher loop).
For windows, you could also queue an APC to that thread that calls RaiseException(...) or throws an exception, (although I would avoid the latter, since that crosses API boundaries), but that also implies that the thread will put itself into an alertable state. And I don't really recommend it.