Can a Win32 C++ Process Kill Itself?


On Windows, can a process kill itself? Let’s verify this by writing a small piece of C++ code, compiled by GNU C++ compiler 4.6, Windows 32-bit. First, we would need to invoke the Win32 API GetCurrentProcessId to get the process ID (type of DWORD) for the current process. And then kill it. However, the Win32 API does not provide a straigtforward KillProcessById and we need to OpenProcess first and TerminateProcess. Therfore, we can have such function to kill any process (if permissions allow you to) by PID.

1
2
3
4
5
void KillProcessById(DWORD pid) {
    HANDLE hnd;
    hnd = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, TRUE, pid);
    TerminateProcess(hnd, 0);
}
void KillProcessById(DWORD pid) {
	HANDLE hnd;
	hnd = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, TRUE, pid);
	TerminateProcess(hnd, 0);
}

Now, let’s verify this by:

1
2
3
4
5
6
7
8
#include <windows.h>
 
int main() {
    DWORD pid = GetCurrentProcessId();
    KillProcessById(pid);
    cout << "https://helloacm.com" << endl;
    return 0;
}
#include <windows.h>

int main() {
    DWORD pid = GetCurrentProcessId();
    KillProcessById(pid);
    cout << "https://helloacm.com" << endl;
    return 0;
}

The process is killed before printing message on the console and therefore the answer is YES, a process can kill itself.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
231 words
Last Post: How to Empty Recycle Bin when it hangs due to lots of files?
Next Post: How to Cache Google QR Image using PHP?

The Permanent URL is: Can a Win32 C++ Process Kill Itself?

Leave a Reply