Killing a "Critical Process" In Windows (C/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.

Related

How to kill my program IMMEDIATELY

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.

How to get the number of timers in a process?

I'm having exactly the same problem described here:
timer_create() : -1 EAGAIN (Resource temporarily unavailable)
in short, some process is reserving a lot of timers via timer_create but never release them.
What I cannot figure out is how to determine the process affected by the leak in our production environment.
How could I know what process is the bad one, without randomly killing all the running stuff?
Any /proc/`pidof myprocess`/ debug info that tell me how many timers are reserved?
Thank you in advance!
Why yes, actually. Use the stap tool to trace system calls and determine which calls processes make most often.
The SystemTap Beginners Guide is a good resource. In particular, see the script on this page for an example of counting specific system calls per process.

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.

How to terminate a QThread?

QThread::terminate() documentation states that it is discouraged to terminate a thread by calling this function.
In my program, I need to terminate a thread before it finishes execution. The thread is performing some heavy computation and I want the user to have control to stop calculation.
How can I do that instead of calling QThread::terminate()?
Set a flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.
Using flags is an obvious and the most common way to do the trick, but if you are working on a linux/unix platform I would advise you to use pipes instead. I had the same issue where I used a flag (this makes the code threadunsafe, and bugs arising out of such a flag are hard to trace), then I changed the implementation to use pipes which were an efficient way to do the needful.
If you want, for a linux platform I can show you how to use pipes to terminate a QThread.
You may also have windows equivalent of pipes, which I don't know much about as I haven't done much of programming on Windows platform.
Hope this helps
Best is to use flag + mutex which will make the solution thread safe.