win32 - 找出占用文件的进程id和name

日常文件操作的时候,在删除或者移动某个文件的时候,发现它被某些进程占用了。

那么下面的代码就可以帮助我们找出这些进程的id和name。

原理:

将资源注册到Restart Manager会话。重新启动管理器使用在会话中注册的资源列表来确定必须关闭并重新启动哪些应用程序和服务。

代码:

#include <windows.h>
#include <RestartManager.h>
#include <stdio.h>
#pragma comment(lib,"Rstrtmgr.lib")
int __cdecl wmain(int argc, WCHAR** argv)
{
    DWORD dwSession;
    WCHAR szSessionKey[CCH_RM_SESSION_KEY + 1] = { 0 };
    DWORD dwError = RmStartSession(&dwSession, 0, szSessionKey);
    wprintf(L"RmStartSession returned %d\n", dwError);
    if (dwError == ERROR_SUCCESS) {
        PCWSTR pszFile = L"test.txt";
        dwError = RmRegisterResources(dwSession, 1, &pszFile,
            0, NULL, 0, NULL);
        wprintf(L"RmRegisterResources(%ls) returned %d\n",
            pszFile, dwError);
        if (dwError == ERROR_SUCCESS) {
            DWORD dwReason;
            UINT i;
            UINT nProcInfoNeeded;
            UINT nProcInfo = 10;
            RM_PROCESS_INFO rgpi[10];
            dwError = RmGetList(dwSession, &nProcInfoNeeded,
                &nProcInfo, rgpi, &dwReason);
            wprintf(L"RmGetList returned %d\n", dwError);
            if (dwError == ERROR_SUCCESS) {
                wprintf(L"RmGetList returned %d infos (%d needed)\n",
                    nProcInfo, nProcInfoNeeded);
                for (i = 0; i < nProcInfo; i++) {
                    wprintf(L"%d.ApplicationType = %d\n", i,
                        rgpi[i].ApplicationType);
                    wprintf(L"%d.strAppName = %ls\n", i,
                        rgpi[i].strAppName);
                    wprintf(L"%d.Process.dwProcessId = %d\n", i,
                        rgpi[i].Process.dwProcessId);
                    HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
                        FALSE, rgpi[i].Process.dwProcessId);
                    if (hProcess) {
                        FILETIME ftCreate, ftExit, ftKernel, ftUser;
                        if (GetProcessTimes(hProcess, &ftCreate, &ftExit,
                            &ftKernel, &ftUser) &&
                            CompareFileTime(&rgpi[i].Process.ProcessStartTime,
                                &ftCreate) == 0) {
                            WCHAR sz[MAX_PATH];
                            DWORD cch = MAX_PATH;
                            if (QueryFullProcessImageNameW(hProcess, 0, sz, &cch) &&
                                cch <= MAX_PATH) {
                                wprintf(L"  = %ls\n", sz);
                            }
                        }
                        CloseHandle(hProcess);
                    }
                }
            }
        }
        RmEndSession(dwSession);
    }
    return 0;
}

相关: How do I find out which process has a file open?

posted @ 2020-12-28 17:30  strive-sun  阅读(388)  评论(0编辑  收藏  举报