How to get a process file descriptor?

I am trying to get the file descriptor of any running C ++ process. This is my code:

#include <windows.h> #include <process.h> #include <Tlhelp32.h> #include <winbase.h> #include <string.h> void killProcessByName(const char *filename) { HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL); PROCESSENTRY32 pEntry; pEntry.dwSize = sizeof (pEntry); BOOL hRes = Process32First(hSnapShot, &pEntry); while (hRes) { if (strcmp(pEntry.szExeFile, filename) == 0) { HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0, (DWORD) pEntry.th32ProcessID); if (hProcess != NULL) { CloseHandle(hProcess); } } hRes = Process32Next(hSnapShot, &pEntry); } CloseHandle(hSnapShot); } int main() { killProcessByName("WINWORD.EXE"); return 0; } 

The code works fine, but the required handle is not freed. Is there any problem regarding the comparison ( strcmp )? Or is there something else I'm doing wrong?

+4
source share
1 answer

Using CloseHandle here is completely correct, it is just an assumption that this is actually wrong. It closes the descriptor that OpenProcess just opened, and will in no way help in changing (deleting or renaming) the executable file, since this file remains open inside the OS. The OS keeps the file open, because the executable files (and DLLs) are loaded "in demand", which means that the OS does not download the entire executable file at once, it only downloads what is actually required at the moment. Later, when you need code that has not been run before, it loads these bits.

+1
source

Source: https://habr.com/ru/post/1494267/


All Articles