C ++ Windows - 如何从其PID获取进程路径 [英] C++ Windows - How to get process path from its PID

查看:1166
本文介绍了C ++ Windows - 如何从其PID获取进程路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I retrieve a process's fully-qualified path from its PID using C++ on Windows?

推荐答案

调用 OpenProcess 获取处理与您的PID相关的过程。一旦您拥有此过程的句柄,请调用 GetModuleFileNameEx 以获取其完全限定路径。不要忘记调用 CloseHandle

Call OpenProcess to get a handle to the process associated with your PID. Once you have a handle to the process, call GetModuleFileNameEx to get its fully-qualified path. Don't forget to call CloseHandle when you're finished using the process handle.

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

Here's a sample program that performs the required calls (replace 1234 with your 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获取进程路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆