How to kill my program IMMEDIATELY - c++

How can I terminate my program (using code) immediately.
I don't want destructors called.
I don't want any hooks to execute.
I just want the bare minimum way to kill the program.
(I'm not looking for answers that say this is not kosher. I know it's not.)
EDIT: Looking for Windows and Linux solutions.
EDIT2: I've tried exit, _exit, abort, and terminate without success on Windows.
EDIT3: While I don't yet have access to a Linux box, I was able to successfully kill my Windows program with the following code:
int pid = _getpid();
char buff[256];
sprintf(buff, "taskkill /pid %d /f", pid);
system(buff);

Just call _exit(), available on both Linux and Windows. It won't produce a core-dump like abort() will.
Edit: If _exit() isn't good enough for you, you'll probably have to go platform-specific.
On Windows, you can call TerminateProcess(), which is, as far as I know, the most forceful/immediate method to kill a process exposed by the Windows API (though if there's a more forceful one I'd love to learn about it).
On Linux, raising SIGKILL might be better, as suggested by Jeffery Thomas. I actually don't know if SIGKILL is more forceful/immediate than _exit() or not.
Both of these methods are asynchronous.

On POSIX compliant UNIX systems, raise(SIGKILL) will do what you want.
For Windows, TerminateProcess(GetCurrentProcess(),0) is what I would look at first. NOTE: This could cause problems for globally shared DLL's.
As a final comment, you didn't give any details, but for whatever you are trying to do, you're doing it the wrong way if this is your way out.

Use _exit(). This will kill your program immediatly.

Try calling the abort() function in C, or std::terminate in C++.
(terminate is also a C function in Visual C++, but it's nonstandard.)

In C++11 _Exit (note: uppercase E) is specified as §18.5/3
” The program is terminated without executing destructors for objects of automatic, thread, or
static storage duration and without calling functions passed to atexit()
If you want possible handlers to execute then you can instead call std::quick_exit, which calls registered handlers and then _Exit.

Related

Keep running the program after SIGABRT c++ signal

I use a third library in my c++ program which under certain circumstances emits SIGABRT signal. I know that trying to free non-initialized pointer or something like this can be the cause of this signal. Nevertheless I want to keep running my program after this signal is emitted, to show a message and allow the user to change the settings, in order to cope with this signal.
(I use QT for developing.)
How can I do that?
I use a third library in my c++ program which under certain circumstances emits SIGABRT signal
If you have the source code of that library, you need to correct the bug (and the bug could be in your code).
BTW, probably SIGABRT happens because abort(3) gets indirectly called (perhaps because you violated some conventions or invariants of that library, which might use assert(3) - and indirectly call abort). I guess that in caffe the various CHECK* macros could indirectly call abort. I leave you to investigate that.
If you don't have the source code or don't have the capacity or time to fix that bug in that third party library, you should give up using that library and use something else.
In many cases, you should trust external libraries more than your own code. Probably, you are abusing or misusing that library. Read carefully its documentation and be sure that your own code calling it is using that library correctly and respects its invariants and conventions. Probably the bug is in your own code, at some other place.
I want to keep running my program
This is impossible (or very unreliable, so unreasonable). I guess that your program has some undefined behavior. Be very scared, and work hard to avoid UB.
You need to improve your debugging skills. Learn better how to use the gdb debugger, valgrind, GCC sanitizers (e.g. instrumentation options like -fsanitize=address, -fsanitize=undefined and others), etc...
You reasonably should not try to handle SIGABRT even if in principle you might (but then read carefully signal(7), signal-safety(7) and hints about handling Unix signals in Qt). I strongly recommend to avoid even trying catching SIGABRT.
Unfortunately, you can't.
SIGABRT signal is itself sent right after abort()
Ref:
https://stackoverflow.com/a/3413215/9332965
You can handle SIGABRT, but you probably shouldn't.
The "can" is straightforward - just trap it in the usual way, using signal(). You don't want to return from this signal handler - you probably got here from abort() - possibly originally from assert() - and that function will exit after raising the signal. You could however longjmp() back to a state you set up earlier.
The "shouldn't" is because once SIGABRT has been raised, your data structures (including those of Qt and any other libraries) are likely in an inconsistent state and actually using any of your program's state is likely to be unpredictable at best. Apart from exiting immediately, there's not much you can do other than exec() a replacement program to take over in a sane initial state.
If you just want to show a friendly message, then you perhaps could exec() a small program to do that (or just use xmessage), but beware of exiting this with a success status where you would have had an indication of the SIGABRT otherwise.
Unfortunately there isn't much you can do to prevent SIGABRT from terminating your program. Not without modifying some code that was hopefully written by you.
You would either need to change code to not throw an abort, or you would have to spawn a new process that runs the code instead of the current process. I do not suggest you use a child process to solve this problem. It's most likely caused by misuse of an api or computer resources, such as low memory.

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.

How to terminate program in C++

When I exit my C++ program it crashes with errors like:
EAccessViolation with mesage 'Access violation at address 0...
and
Abnormal Program Termination
It is probably caused by some destructor because it happens only when the application exits. I use a few external libraries and cannot find the code that causes it. Is there a function that forces immediate program exit (something like kill in Linux) so that memory would have to be freed by the operating system? I could use this function in app exit event.
I know that it would be a terrible solution because it'd just hide the problem.
I'm just asking out of sheer curiosity, so please don't give me -1 :)
I tried exit(0) from stdlib but it didn't help.
EDIT:
Thanks for your numerous replies:)
I use Builder C++ 6 (I know it's outdated but for some reasons I had to use it). My app uses library to neural networks (FANN). Using the debugger I found that program crashes in:
~neural_net()
{
destroy();
}
destroy() calls multiple time another function fann_safe_free(ptr), that is:
#define fann_safe_free(x) {if(x) { free(x); x = NULL; }}
The library works great, problem only appears when it does cleaning. That's why I asked about so brutal solution. My app is multi-threaded but other threads operate on different data.
I will analyze my code for the n-th time(the bug must be somewhere), thanks for all your tips :)
You should fix the problem.
First step: find at check all functions you register with atexit() (not many I hope)
Second step: find all global variables and check their destructors.
Third Step: find all static function variables check their destructors.
But otherwise you can abort.
Note: abort is for Abnormal program termination.
abort()
The difference: (note letting an application leave the main function is the equivalent of exit())
exit()
Call the functions registered with the atexit(3) function, in the reverse order of their registration. This includes the destruction of all global (static storage duration) variables.
Flush all open output streams.
Close all open streams.
Unlink all files created with the tmpfile(3) function.
abort()
Flush all open output streams.
Close all open streams.
It's a terrible solution for more than one reason. It will hide the problem (maybe), but it could also corrupt data, depending on the nature of your application.
Why don't you use a debugger and try to find out what is causing the error?
If your application is multi-threaded, you should make sure that all threads are properly shut down before exiting the application. This is a fairly common cause of that type of error on exit, when a background thread is attempting to use memory/objects that have already been destructed.
Edit:
based on your updated question, I have the following suggestions:
Try to find out more specifically what is causing the crash in the destructor.
The first thing I would do is make sure that it's not trying to destruct a NULL object. When you get your crash in ~neural_net in your debugger, check your "this" pointer to make sure it's not NULL. If it is, then check your call-stack and see where it's being destructed, and do a check to make sure it's not NULL before calling delete.
If it's not NULL, then I would unroll that macro in destroy, so you can see if it's crashing on the call to free.
You could try calling abort(); (declared in <stdlib.h> and in <process.h>)
The version in VisualC++, however, will print a warning message as it exits: "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information."
On Linux/UNIX you can use _exit:
#include <unistd.h>
void _exit(int status);
The function _exit() is like exit(), but does not call any functions registered with atexit() or on_exit(). Whether it flushes standard I/O buffers and removes temporary files created with tmpfile(3) is implementation dependent. On the other hand, _exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish. If the delay is undesired, it may be useful to call functions like tcflush() before calling _exit(). Whether any pending I/O is cancelled, and which pending I/O may be cancelled upon _exit(), is implementation-dependent.
Have you tried the gruesome step by step? If you're project/solution is simply to large to do so maybe you could try segmenting it assuming you use a modular build and test each component indivdually. Without any code or visible destructors abstract advice is all I can give you I'm afraid. But nonetheless I hope trying to minimize the debugging field will help in some way.
Good luck with getting an answer :)
That immediate program exit (and yes, that's a terrible solution) is abort()
That happens most likely because a NULL pointer is being accessed. Depending on your OS try getting a stack trace and identify the culprit, don't just exit.
If you use linux, valgrind should solve your problem.
but if it is windows, try one of these: MemoryValidator, BoundsChecker or other tools like these.
Simply close your application is not the best way to deal with bugs ...

COM Pointers and process termination

Can an unreleased COM pointer to an external process (still alive) cause that process to hang on destruction?
Even with TerminateProcess called on it?
Process A has a COM interface pointer reference to Process B, now Process B issues a TerminateProcess on A, if some COM interface pointer to Process B in Process A is not released properly, could it be that the process hangs on termination?
I want to know as I have a project where a child process hangs on killing, even though TerminateProcess is called if the normal close procedure fails. When it hangs on killing, it doesn't just hang itself, but also it's parent process, which is disastrous since this is running in a production environment. So I'm trying to see where there's possibilities of it going wrong.
No. TerminateProcess does just that -- completely destroys the process. Raymond Chen has a few words to say about that....
EDIT: He also has some more detailed articles detailing exactly how process shutdown occurs. It however is not related to TerminateProcess.
Well, yes, it is technically possible for TerminateProcess not to terminate the process. If there's a kernel thread executing an I/O request that never ends then the process cannot exit. Easy to diagnose, you'll see the process in Taskmgr.exe's Processes tab with a handle count of one. Vista had a CancelIo improvement to fix this, I think Raymond talked about that too.
Which is only very remotely associated with COM. Grasping at straws: an out-of-process COM server doesn't deal with TerminateProcess of a client well, Windows cannot automatically call Release() on the interface pointers. It will keep running forever. Until somebody calls TerminateProcess, usually the Windows shutdown code or TaskMgr.exe
Do make sure to edit your question and explain why you even asked it.

Killing a "Critical Process" In Windows (C/C++)

What is the best way to kill a critical process?
It's critical for a reason so you probably shouldn't be killing it at all. The best way is to shut down the box lest you leave it in a dangerous state.
If you choose to ignore my warning, here is some sample C++ code to do it.
This knowledge base article describes how to do it. You first call SeDebugPrivilege() to obtain the privileges to terminate processes, then you call OpenProcess() with the PROCESS_TERMINATE flag to get a handle to the process you wish to terminate, and then finally you call TerminateProcess() to terminate the process.
Yup, do what Adam suggested. Then watch as your machine bluescreens since you just terminated a critical process :) (btw, to be clear: Adam's suggestion is 100% accurate, it's not my intent to criticize it at all).
Why do you want to do this? There's a reason they're called critical processes.
Invoking the kill function in signal.h is one way to killing a process in C. No idea about the alternations in C++.
Killing a Process in C
Edit : Have a look on this code.
WIN 32 API example
I guess, the question was how to kill critical process without BSoD. To do this you need first to remove criticality bit, and only after that call terminate function.