簡體   English   中英

從PID檢索進程運行目錄

[英]Retrieving process running dir from PID

嘗試使用PID檢索進程的運行目錄。 我正在使用FindWindow()GetWindowThreadProcessId()獲取PID,其結果與任務管理器中顯示的進程ID相同,因此我認為它是正確的。

當使用GetModuleFileNameEx() ,我得到的似乎是一個內存地址,而不是生成路徑。

auto wnd = FindWindow(nullptr, L"prog");
while (wnd == nullptr)
{
    wnd = FindWindow(nullptr, L"prog");
}

TCHAR fBuf[MAX_PATH]; // buffer for path
DWORD procId; // process id
GetWindowThreadProcessId(wnd, &procId); // get process id
std::cout << procId << std::endl; // results in correct pid
auto procHdl = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, procId); // create handle for process
if (procHdl != NULL) {
    if (GetModuleFileNameEx(procHdl, 0, fBuf, MAX_PATH) == 0) {
        std::cerr << "Failed to get module filename." << std::endl;
    }
    else {
        std::cout << "Module filename is: " << fBuf << std::endl;
    }

    CloseHandle(procHdl);
}

樣本輸出為:

10488
Module filename is: 008CF93C

我也使用GetProcessImageFileNname()獲得了相同的結果。

要獲取程序的目錄,請首先使用GetModuleFileNameEx獲取程序路徑,然后您的目錄將從第一個字符開始到找到的最后一個反斜杠開始。

例:

程序為:“ C:\\ Windows \\ notepad.exe”;
目錄是:“ C:\\ Windows”;

在代碼中:

DWORD pid = 104;
CHAR ProgramFile[MAX_PATH];
std::string DirectoryPath;
HANDLE hProcess = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, FALSE, pid);
GetModuleFileNameExA(hProcess, NULL, ProgramFile, MAX_PATH);
DirectoryPath = ProgramFile;
DirectoryPath = DirectoryPath.substr(0, DirectoryPath.find_last_of('\\'));
std::cout << "ProgramFile: " << ProgramFile << endl;
std::cout << "Directory: " << DirectoryPath.c_str();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM