C++ 查看当前占用该文件的进程
参考: https://blog.csdn.net/cwjjamk/article/details/9857013
https://www.shuzhiduo.com/A/kjdwDO6EzN/
https://www.cnblogs.com/iBinary/p/11362823.html
https://stackoverflow.com/questions/1219951/win32api-how-to-get-file-name-of-process-from-process-handle
https://blog.csdn.net/proglovercn/article/details/42734379
https://bbs.pediy.com/thread-144945-1.htm
https://www.cnblogs.com/Philip-Tell-Truth/p/6932966.html
https://www.xuebuyuan.com/1663928.html
http://developer.zhiding.cn/2008/0805/1039808.shtml
代码:
// ConsoleApplication3.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
include "pch.h"
include <stdio.h>
include <stdlib.h>
//#include "stdafx.h"
include <malloc.h>
include <windows.h>
include <tlhelp32.h>
include
include <tchar.h>
include <psapi.h>
include
include
//#pragma comment(linker,"/subsystem:console")
typedef LONG NTSTATUS;
define NT_SUCCESS(status) ((NTSTATUS)(status)>=0)
define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
using namespace std;
/////////***ZwQuerySystemInformation////////////////////
//systemInformationClass -> need SystemHandleInformation to find all the system handles
typedef enum _SYSTEM_INFORMATION_CLASS
{
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemNotImplemented1,
SystemProcessesAndThreadsInformation,
SystemCallCounts,
SystemConfigurationInformation,
SystemProcessorTimes,
SystemGlobalFlag,
SystemNotImplemented2,
SystemModuleInformation,
SystemLockInformation,
SystemNotImplemented3,
SystemNotImplemented4,
SystemNotImplemented5,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemInstructionEmulationCounts,
SystemInvalidInfoClass1,
SystemCacheInformation,
SystemPoolTagInformation,
SystemProcessorStatistics,
SystemDpcInformation,
SystemNotImplemented6,
SystemLoadImage,
SystemUnloadImage,
SystemTimeAdjustment,
SystemNotImplemented7,
SystemNotImplemented8,
SystemNotImplemented9,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemLoadAndCallImage,
SystemPrioritySeparation,
SystemNotImplemented10,
SystemNotImplemented11,
SystemInvalidInfoClass2,
SystemInvalidInfoClass3,
SystemTimeZoneInformation,
SystemLookasideInformation,
SystemSetTimeSlipEvent,
SystemCreateSession,
SystemDeleteSession,
SystemInvalidInfoClass4,
SystemRangeStartInformation,
SystemVerifierInformation,
SystemAddVerifier,
SystemSessionProcessedInformation
}SYSTEM_INFORMATION_CLASS;
//systemHandleInformation struct def and the systemHandleTableEntryInfo def
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
}SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
}SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
//winapi ZwQuerySystemInformation for find system handles info
typedef NTSTATUS(WINAPI * pfnZwQuerySystemInformation)
(
IN ULONG SyetemInformationClass,
IN OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength
);
pfnZwQuerySystemInformation ZwQuerySystemInformation;
/////////***ZwQuerySystemInformation_____enddddd////////////////////
//////ZwQueryInformationFile****/////////////////////
//fileinformationClass def
typedef enum _FILE_INFORMATION_CLASS
{
// end_wdm
FileDirectoryInformation = 1,
FileFullDirectoryInformation, // 2
FileBothDirectoryInformation, // 3
FileBasicInformation, // 4 wdm
FileStandardInformation, // 5 wdm
FileInternalInformation, // 6
FileEaInformation, // 7
FileAccessInformation, // 8
FileNameInformation, // 9
FileRenameInformation, // 10
FileLinkInformation, // 11
FileNamesInformation, // 12
FileDispositionInformation, // 13
FilePositionInformation, // 14 wdm
FileFullEaInformation, // 15
FileModeInformation, // 16
FileAlignmentInformation, // 17
FileAllInformation, // 18
FileAllocationInformation, // 19
FileEndOfFileInformation, // 20 wdm
FileAlternateNameInformation, // 21
FileStreamInformation, // 22
FilePipeInformation, // 23
FilePipeLocalInformation, // 24
FilePipeRemoteInformation, // 25
FileMailslotQueryInformation, // 26
FileMailslotSetInformation, // 27
FileCompressionInformation, // 28
FileObjectIdInformation, // 29
FileCompletionInformation, // 30
FileMoveClusterInformation, // 31
FileQuotaInformation, // 32
FileReparsePointInformation, // 33
FileNetworkOpenInformation, // 34
FileAttributeTagInformation, // 35
FileTrackingInformation, // 36
FileIdBothDirectoryInformation, // 37
FileIdFullDirectoryInformation, // 38
FileValidDataLengthInformation, // 39
FileShortNameInformation, // 40
FileMaximumInformation
// begin_wdm
} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
//ZwQueryInformationFile def
typedef struct _IO_STATUS_BLOCK
{
union
{
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Informatin;
}IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
typedef NTSTATUS(WINAPI *pnfZwQueryInformationFile)
(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN DWORD Length,
IN FILE_INFORMATION_CLASS FileInformationClass
);
pnfZwQueryInformationFile ZwQueryInformationFile;
typedef NTSTATUS(WINAPI * pfnNtQueryInformationFile)
(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass
);
pfnNtQueryInformationFile NtQueryInformationFile;
//////ZwQueryInformationFile_____enddddd****/////////////////////
/////****************find file handle type*****************************///////////////
//to describe the handle informatin
typedef struct _SYSTEM_HANDLE
{
ULONG uIdProcess;
UCHAR ObjectType; //filetype
UCHAR Flags;
USHORT Handle;
PVOID pObject;
ACCESS_MASK GrantedAccess;
} SYSTEM_HANDLE, *PSYSTEM_HANDLE;
//load ntdll
void InitFunction()
{
HMODULE hDll = LoadLibrary(TEXT("ntdll.dll"));
if (NULL == hDll)
{
return;
}
ZwQuerySystemInformation = reinterpret_cast
//ZwQueryInformationFile = reinterpret_cast
NtQueryInformationFile = reinterpret_cast
if (NULL == ZwQuerySystemInformation)
return;
}
PVOID RetSystemHandleInformation()
{
PULONG szBuffer = NULL;
DWORD dwSize = 0x1000;
DWORD dwRetSize = 0;
NTSTATUS ntStatus;
szBuffer = new ULONG[dwSize];
if (NULL == szBuffer)
{
return NULL;
}
do
{
ntStatus = ZwQuerySystemInformation(SystemHandleInformation, szBuffer, dwSize, &dwRetSize);
if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) //??????.??????
{
delete[] szBuffer;
szBuffer = new ULONG[dwSize *= 2];
}
else
{
if (!NT_SUCCESS(ntStatus))
{
delete[] szBuffer;
return NULL;
}
}
} while (ntStatus == STATUS_INFO_LENGTH_MISMATCH);
return szBuffer;
}
//get Filehandle type
UCHAR GetFileHandleType()
{
HANDLE hFile;
PSYSTEM_HANDLE_INFORMATION Info;
ULONG r;
UCHAR Result = 0;
hFile = CreateFile(_T("NUL"), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
if (hFile != INVALID_HANDLE_VALUE)
{
Info = reinterpret_cast<PSYSTEM_HANDLE_INFORMATION>(RetSystemHandleInformation());
if (Info)
{
for (r = 0; r < Info->NumberOfHandles; r++)
{
if (Info->Handles[r].HandleValue == (USHORT)hFile && Info->Handles[r].UniqueProcessId == GetCurrentProcessId())
{
Result = Info->Handles[r].ObjectTypeIndex;
break;
}
}
}
CloseHandle(hFile);
}
return Result;
}
/////****************find file handle type____endddddd*****************************///////////////
//////***************get file name ***************************////////////////////
typedef struct _FILE_NAME_INFORMATION
{
ULONG FileNameLength;
WCHAR FileName[255];
}FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION;
typedef struct _NM_INFO
{
HANDLE hFile;
FILE_NAME_INFORMATION Info;
WCHAR Name[MAX_PATH];
} NM_INFO, *PNM_INFO;
DWORD WINAPI GetFileNameThread(PVOID lpParameter)
{
PNM_INFO NmInfo = (PNM_INFO)lpParameter;
IO_STATUS_BLOCK IoStatus;
NtQueryInformationFile(NmInfo->hFile, &IoStatus, &NmInfo->Info, sizeof(NM_INFO) - sizeof(HANDLE), FileNameInformation);
//NtQueryInformationFile(NmInfo->hFile, &IoStatus, &NmInfo->Info, 256, FileNameInformation);
return 0;
}
void GetFileName(HANDLE hFile, PCHAR TheName)
{
HANDLE hThread;
HANDLE hHeap = GetProcessHeap();
PNM_INFO Info = (PNM_INFO)HeapAlloc(hHeap, 0, sizeof(NM_INFO));
Info->hFile = hFile;
hThread = CreateThread(NULL, 0, GetFileNameThread, Info, 0, NULL);
if (WaitForSingleObject(hThread, 60000) == WAIT_TIMEOUT) //INFINITE WAIT_TIMEOUT
//if (WaitForSingleObject(hThread, 50) != WAIT_OBJECT_0)
{
TerminateThread(hThread, 0);
}
CloseHandle(hThread);
memset(TheName, 0, MAX_PATH);
WideCharToMultiByte(CP_ACP, 0, Info->Info.FileName,Info->Info.FileNameLength >> 1, TheName, MAX_PATH, NULL, NULL);
HeapFree(hHeap, 0, Info);
}
//////***************get file name_enddddddddddddddd ***************************////////////////////
////////////update the process access///////////////
bool AdjustProcessTokenPrivilege()
{
LUID luidTmp;
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
//OutputDebugString("AdjustProcessTokenPrivilege OpenProcessToken Failed ! \n");
cout << "AdjustProcessTokenPrivilege OpenProcessToken Failed !" << endl;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luidTmp))
{
//OutputDebugString("AdjustProcessTokenPrivilege LookupPrivilegeValue Failed !");
cout << "AdjustProcessTokenPrivilege LookupPrivilegeValue Failed !" << endl;
CloseHandle(hToken);
return FALSE;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = luidTmp;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL))
{
//OutputDebugString("AdjustProcessTokenPrivilege AdjustTokenPrivileges Failed ! \n");
cout << "AdjustProcessTokenPrivilege AdjustTokenPrivileges Failed !" << endl;
CloseHandle(hToken);
return FALSE;
}
CloseHandle(hToken);
return true;
}
/*
typedef struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
ifdef MIDL_PASS
[size_is(MaximumLength / 2), length_is((Length) / 2)] USHORT * Buffer;
else // MIDL_PASS
PWSTR Buffer;
endif // MIDL_PASS
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _OBJECT_NAME_INFORMATION
{
UNICODE_STRING Name;
} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION;
typedef struct _OBJECT_ATTRIBUTES
{
ULONG Length;
PVOID RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor;
PVOID SecurityQualityOfService;
}OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
typedef struct _CLIENT_ID
{
HANDLE UniqueProcess;
HANDLE UniqueThread;
}CLIENT_ID, *PCLIENT_ID;
*/
int main()
{
PSYSTEM_HANDLE_INFORMATION Info;
ULONG r;
CHAR Name[MAX_PATH];
CHAR *NameInput=new CHAR[25];
//string NameInput;
HANDLE hProcess, hFile;
InitFunction();
UCHAR ObFileType = GetFileHandleType();
PVOID pBuffER = NULL;
wcout << "Input file name: " << endl;
cin >> NameInput;
//while ((NameInput = cin.get()) != EOF)
// cout << NameInput;
cout << "Begin to find -> " << NameInput << endl;
Info = reinterpret_cast<PSYSTEM_HANDLE_INFORMATION>(RetSystemHandleInformation());
if (Info)
{
for (r = 0; r < Info->NumberOfHandles; r++)
{
if (Info->Handles[r].ObjectTypeIndex == ObFileType)
{
bool UpAccessRet = AdjustProcessTokenPrivilege();
hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, Info->Handles[r].UniqueProcessId);
if (hProcess)
{
if (DuplicateHandle(hProcess, (HANDLE)Info->Handles[r].HandleValue, GetCurrentProcess(), &hFile, 0, FALSE, DUPLICATE_SAME_ACCESS))
{
GetFileName(hFile, Name);
//if (strstr(Name, "shell32") != NULL) //shell32 UpdaterUtilities
if (strstr(Name, NameInput) != NULL) //shell32
{
//printf("%s\n", Name);
wcout << Info->Handles[r].UniqueProcessId << endl;
PROCESSENTRY32 PE32;
PE32.dwSize = sizeof(PE32);
HANDLE hProcessSnao = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnao == INVALID_HANDLE_VALUE)
{
printf("CreateToolHelp32Snapshot failed");
}
BOOL Bmore = ::Process32First(hProcessSnao, &PE32);
while (Bmore)
{
if (PE32.th32ProcessID == Info->Handles[r].UniqueProcessId)
{
//printf("the object name is %s", PE32.szExeFile);
wcout << PE32.szExeFile << endl;
break;
}
Bmore = ::Process32Next(hProcessSnao, &PE32);
}
}
CloseHandle(hFile);
}
CloseHandle(hProcess);
}
}
}
}
printf("hahah");
system("pause");
}