Why does the following code always print out 127 (“The specified procedure could not be found.”) even though it finds “firefox.exe” and terminates it successfully??
#include<Windows.h>
#include <TlHelp32.h>
#include<iostream>
using namespace std;
int main( int, char *[] )
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (_tcscmp(entry.szExeFile, TEXT("firefox.exe")) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
DWORD d = GetLastError();
cout<<d<<'\n';
TerminateProcess(hProcess,0);
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
return 0;
}
You need to check return values for specific functions before checking
GetLastError.GetLastErrorwill always return the last error code that was set by by an API function. However, not all functions will set the last-error code when they succeed. So the result fromGetLastErrormay be an error code that was set at some other part of your program.So in your case, according to the MSDN docs for
OpenProcess, the function will returnNULLif it fails. Hence there’s no need to look atGetLastErrorifOpenProcessreturns other thanNULL.Note that the last-error code is unique to the current thread.