简体   繁体   中英

How to get file handle of a process?

I'm trying to get file handle of any running process in C++ . 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 is working fine but the required handle isn't getting released. Is there some problem in the comparison ( strcmp ) part? Or is there something else I'm doing wrong?

The use of CloseHandle here is perfectly correct, it's just the assumption about what it actually does that is incorrectly. It closes the handle just opened by OpenProcess , and will not in any way help in being able to alter (delete or rename) the executable file, because that file is held open inside the OS. The OS holds the file open because executable files (and DLLs) are "demand loaded", which means that the OS doesn't load the entire executable at once, it only loads what it actually needs for the time being. Later on, when code that hasn't been run before is needed, it loads those bits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM