Question

We've got issues with our program potentially hanging in certain situations, is there a way to search and destroy your own program with windows calls without using task manager. It probably wouldn't make sense to include this in the program itself, but as a bundled thing no one would see.

What's the best way to go about doing this, how deep do I need to dig to stop my program and how shallow should I keep to make sure I don't crash the OS?

Was it helpful?

Solution

You could create a .bat file and put a Taskkill command in it to forcefully terminate your application. The command would look something like this:

taskkill /f /im notepad.exe

OTHER TIPS

Although you should probably fix the situation in which it hangs, one way you could have the program kill itself is to spawn a new thread when you launch the app, and have that thread poll the application and kill it if necessary.

Killing a thread in windows.

One option would be to write a Windows Service that serves as a Watchdog. You could find your program by it's .exename and then you need some way to determine if it hangs (for example some simple Inter-Process-Communication or even a Client/Server thing) and restart it if necessary.

That is hardly "no one would see" though.

You can terminate a process using TerminateProcess. You'll need to determine the target process id using EnumProcesses and then call OpenProcess to obtain a handle to the process in order to terminate it.

You can enumerate running processes using the EnumProcesses() function. This will let you search for the process name, and get the PID. With the PID, you can open a HANDLE to the process which you need in order to call TerminateProcess() to kill the hung process.

There's an example of how to use EnumProcesses on MSDN.

Some pseudo-code might look something like:

EnumProcesses(pidArray, sizeofArray, &bytesReturned);
for(int i=0; i < bytesReturned/sizeof(DWORD); i++) {
  if(getProcessName(pidArray[i]) == "ourProcess"){
    HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pidArray[i]);
    TerminateProcess(hProc, 0);
  }
}

What about implementing something from the pstools of sysinternals ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top