Search code examples
debuggingprocesstaskkill

Why process doesn't get killed when debugger is attached?


I have simple code in Visual Studio,

#include <iostream>

using std::cout;

int main()
{
    cout << "Hello World";
    return 0;
}

Please refer image as well.

I put breakpoint and started in debug mode. After breakpoint hit, I run following command in cmd.exe (Administrator) to force kill process. And it shows success message.

taskkill /IM debug.exe /F

Still, I can see Debug.exe in Task Manager. Why has not get killed? Is there any alternate way to kill the process?

Please note I cannot use pskill or any other tool from SysInternals.

enter image description here


Solution

  • On Windows all processes have handles. If you've ever used the Win32 API you've probably seen HINSTANCE or HANDLE's.

    According to what I've read and what I've observed, especially the link that I sent to you: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx it's mentioned that

    When a process terminates, its kernel object is not destroyed until all processes that have open handles to the process have released those handles.

    Which suggests that the program will stay 'alive' until all handles have been released, much like files.

    This is just a guess, but when the command prompt writes "the process has been terminated" it might mean that the process has been sent a termination signal which heralds its death.

    I'm by no means an expert on this subject but I think it's safe to say (If no guru's will correct me) that you simply can't kill something that's being used in Windows and your program is being used by the debugger, just like with files. Try sending a kill signal to the debugger too and see if that helps?

    TL;DR: Debugger has a handle to the process (maybe throught the fact that it's might be a child process to the debugger) and therefore you can't kill it until the last handle is yours.