简体   繁体   English

如何从文件名中找到哪个进程对文件有句柄

[英]how to find which process has a handle on a file from the file name

Windows C++ API 中是否有任何内容可以为我提供具有给定文件句柄的进程列表?

From Microsoft's blog: How do I find out which process has a file open?来自 Microsoft 的博客: 如何找出哪个进程打开了文件?

Enter the Restart Manager .进入重启管理器

The official goal of the Restart Manager is to help make it possible to shut down and restart applications which are using a file you want to update.重新启动管理器的官方目标是帮助关闭和重新启动使用您要更新的文件的应用程序。 In order to do that, it needs to keep track of which processes are holding references to which files.为此,它需要跟踪哪些进程持有对哪些文件的引用。 And it's that database that is of use here.这就是这里有用的数据库。 (Why is the kernel keeping track of which processes have a file open? Because it's the converse of the principle of not keeping track of information you don't need: Now it needs the information!) (为什么内核要跟踪哪些进程打开了文件?因为这与不跟踪不需要的信息的原则相反:现在它需要信息!)

Here's a simple program which takes a file name on the command line and shows which processes have the file open.这是一个简单的程序,它在命令行上获取文件名并显示哪些进程打开了该文件。

 #include <windows.h> #include <RestartManager.h> #include <stdio.h> 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 = argv[1]; 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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