C++ Windows - 如何从其 PID 获取进程路径

标签 c++ windows

如何在 Windows 上使用 C++ 从其 PID 中检索进程的完全限定路径?

最佳答案

调用 OpenProcess获取与您的 PID 关联的进程的句柄。一旦您掌握了流程,请调用 GetModuleFileNameEx获得其完全合格的路径。不要忘记调用CloseHandle当您使用完进程句柄时。

这是一个执行所需调用的示例程序(将 1234 替换为您的 PID):

#include <windows.h>
#include <psapi.h> // For access to GetModuleFileNameEx
#include <tchar.h>

#include <iostream>

using namespace std;

#ifdef _UNICODE
  #define tcout wcout
  #define tcerr wcerr
#else
  #define tcout cout
  #define tcerr cerr
#endif

int _tmain(int argc, TCHAR * argv[])
{
  HANDLE processHandle = NULL;
  TCHAR filename[MAX_PATH];

  processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, 1234);
  if (processHandle != NULL) {
    if (GetModuleFileNameEx(processHandle, NULL, filename, MAX_PATH) == 0) {
      tcerr << "Failed to get module filename." << endl;
    } else {
      tcout << "Module filename is: " << filename << endl;
    }
    CloseHandle(processHandle);
  } else {
    tcerr << "Failed to open process." << endl;
  }

  return 0;
}

关于C++ Windows - 如何从其 PID 获取进程路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1933113/

相关文章:

c++ - 如何通过 bash shell cin a c++ 字符串 >= 1024 个字符?

c++ - 当 `std::vector` 调整其内存大小时避免任何自动变量

C++ 位集没有内联?

html 标签在 Qt 中不起作用

c++ - 不能包含 "vcruntime_new_debug.h"

windows - Qt 相当于 Win32 Fibers

c++ - 用数学表达式拆分字符串

c - 如何在不使用 select() 的情况下在特定套接字和特定端口上超时?

windows - Github 在克隆过程中自动删除文件

windows - 赢得批处理 : copy files on different folders