#include <Windows.h>

BOOL SafeTerminateProcess(HANDLE hProcess, UINT uExitCode) {
	DWORD tid, dwCode, dwErr = 0;
	HANDLE hProcessDup = INVALID_HANDLE_VALUE;
	HANDLE hRemoteThread = NULL;
	HINSTANCE hKernel = GetModuleHandleA("Kernel32");

	BOOL bSuccess = FALSE;
	BOOL bDup = DuplicateHandle(GetCurrentProcess(), hProcess, GetCurrentProcess(), &hProcessDup, PROCESS_ALL_ACCESS, FALSE, 0);

	if (GetExitCodeProcess((bDup) ? hProcessDup : hProcess, &dwCode) && (dwCode == STILL_ACTIVE)) {
		FARPROC pfnExitProc = GetProcAddress(hKernel, "ExitProcess");
		hRemoteThread = CreateRemoteThread((bDup) ? hProcessDup : hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pfnExitProc, (PVOID)uExitCode, 0, &tid);
		if (hRemoteThread == NULL)
			dwErr = GetLastError();
	} else {
		dwErr = ERROR_PROCESS_ABORTED;
	}

	if (hRemoteThread) {
		WaitForSingleObject((bDup) ? hProcessDup : hProcess, INFINITE);
		CloseHandle(hRemoteThread);
		bSuccess = TRUE;
	}

	if (bDup)
		CloseHandle(hProcessDup);

	if (!bSuccess)
		SetLastError(dwErr);

	return bSuccess;
}

void main() {
	PROCESS_INFORMATION pi = { 0 };
	STARTUPINFOA si = { sizeof(STARTUPINFOA) };
	CreateProcessA(NULL, "notepad.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

	Sleep(1000);

	SafeTerminateProcess(pi.hProcess, 1);
}


References


신고

티스토리 툴바