1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| #include <stdio.h> #include <windows.h> #include <tchar.h> #include <Psapi.h> #pragma comment (lib,"Psapi.lib") #include <TlHelp32.h> BOOL DosPathToNtPath(LPTSTR pszDosPath, LPTSTR pszNtPath) { TCHAR szDriveStr[500]; TCHAR szDrive[3]; TCHAR szDevName[100]; INT cchDevName; INT i;
if (!pszDosPath || !pszNtPath) return FALSE;
if (GetLogicalDriveStrings(sizeof(szDriveStr), szDriveStr)) { for (i = 0; szDriveStr[i]; i += 4) { if (!lstrcmpi(&(szDriveStr[i]), _T("A:\\")) || !lstrcmpi(&(szDriveStr[i]), _T("B:\\"))) continue;
szDrive[0] = szDriveStr[i]; szDrive[1] = szDriveStr[i + 1]; szDrive[2] = '\0'; if (!QueryDosDevice(szDrive, szDevName, 100)) return FALSE;
cchDevName = lstrlen(szDevName); if (_tcsnicmp(pszDosPath, szDevName, cchDevName) == 0) { lstrcpy(pszNtPath, szDrive); lstrcat(pszNtPath, pszDosPath + cchDevName);
return TRUE; } } }
lstrcpy(pszNtPath, pszDosPath);
return FALSE; }
BOOL GetProcessFullPath(DWORD dwPID, TCHAR pszFullPath[MAX_PATH]) { TCHAR szImagePath[MAX_PATH]; HANDLE hProcess; if (!pszFullPath) return FALSE;
pszFullPath[0] = '\0'; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, dwPID); if (!hProcess) return FALSE;
if (!GetProcessImageFileName(hProcess, szImagePath, MAX_PATH)) { CloseHandle(hProcess); return FALSE; }
if (!DosPathToNtPath(szImagePath, pszFullPath)) { CloseHandle(hProcess); return FALSE; }
CloseHandle(hProcess);
return TRUE; } typedef struct Process { unsigned long* pid; int size; }_Process, *PtrProcess;
int TraversalProcess(void* addr) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hSnapshot) { return NULL; } PtrProcess PidInfo = (PtrProcess)addr; PidInfo->size = 0; PROCESSENTRY32 pe = { 0 }; pe.dwSize = sizeof(PROCESSENTRY32); BOOL fOk; for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe)) { PidInfo->pid[PidInfo->size] = pe.th32ProcessID; PidInfo->size++; } } int main(int argc, char* argv[]) { TCHAR pszFullPath[MAX_PATH] = { 0 }; PtrProcess PidInfo =(PtrProcess)malloc(sizeof(_Process)); PidInfo->pid = (int*)malloc(sizeof(int) * 1024); TraversalProcess(PidInfo); int i = 0; while(i< PidInfo->size) { GetProcessFullPath(PidInfo->pid[i], pszFullPath); _tprintf(_T("%d,%s \r\n"), PidInfo->pid[i], pszFullPath); i++; } free(PidInfo->pid); free(PidInfo); PidInfo->pid = NULL; PidInfo = NULL; return 0; }
|