100分求助,64位系统下C++获取当前所有进程的完整路径

testwwwwww 2014-11-20 11:37:37
进程快照那个TlHelp32.h已经不支持64位,我已经测试过,无法获取64位进程的路径,请不要使用这个。其次,我使用Psapi.h中的某些函数尝试了很久都是失败,百度了很多,也都是错误的、失败的,下载了很多,也差不多都是没用的、骗分的,请问到底该如何获取当前运行中的32位和64位进程的完整路径?感谢!
...全文
1147 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Sping 2014-11-21
  • 打赏
  • 举报
回复

#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
#include <string>
#include <tchar.h>
#include <Psapi.h>
#pragma comment (lib,"Psapi.lib")

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))//查询 Dos 设备名
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);

_tprintf(_T("%d,%s \r\n"),dwPID,pszFullPath);
return TRUE;
}
int main(int argc, char* argv[])
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return NULL;
}
PROCESSENTRY32 pe ={0};
pe.dwSize = sizeof(PROCESSENTRY32);

BOOL fOk;
for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe))
{
TCHAR szProcessName[MAX_PATH] = {0};
GetProcessFullPath(pe.th32ProcessID, szProcessName);
}
return 0;
}


完整程序,不对你来砍我!看截图,32位,64位都有~我要分!!!
赵4老师 2014-11-21
  • 打赏
  • 举报
回复
使用tasklist命令不行吗?
testwwwwww 2014-11-21
  • 打赏
  • 举报
回复
引用 1 楼 tpnndhqc 的回复:

#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
#include <string>
#include <tchar.h>
#include <Psapi.h>
#pragma comment (lib,"Psapi.lib")

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))//查询 Dos 设备名
				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);

	_tprintf(_T("%d,%s \r\n"),dwPID,pszFullPath);
	return TRUE;
}
int main(int argc, char* argv[])
{
	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (INVALID_HANDLE_VALUE == hSnapshot)
	{
		return NULL;
	}
	PROCESSENTRY32 pe ={0};
	pe.dwSize = sizeof(PROCESSENTRY32); 

	BOOL fOk;
	for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe))
	{
		TCHAR szProcessName[MAX_PATH] = {0};
		GetProcessFullPath(pe.th32ProcessID, szProcessName);
	}
	return 0;
}
完整程序,不对你来砍我!看截图,32位,64位都有~我要分!!!
非常感谢!测试完全有效!您也算是给百度这东西的朋友做出了贡献哈!100分给您了!
赵4老师 2014-11-21
  • 打赏
  • 举报
回复
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/dllproc/base/taking_a_snapshot_and_viewing_processes.htm
Taking a Snapshot and Viewing Processes
The following simple console application obtains a list of running processes. First, the GetProcessList function takes a snapshot of currently executing processes in the system using CreateToolhelp32Snapshot, and then it walks through the list recorded in the snapshot using Process32First and Process32Next. For each process in turn, GetProcessList calls the ListProcessModules function which is described in Traversing the Module List, and the ListProcessThreads function which is described in Traversing the Thread List. 

A simple error-reporting function, printError, displays the reason for any failures, which usually result from security restrictions.


#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>

//  Forward declarations:
BOOL GetProcessList( );
BOOL ListProcessModules( DWORD dwPID );
BOOL ListProcessThreads( DWORD dwOwnerPID );
void printError( TCHAR* msg );

void main( )
{
  GetProcessList( );
}

BOOL GetProcessList( )
{
  HANDLE hProcessSnap;
  HANDLE hProcess;
  PROCESSENTRY32 pe32;
  DWORD dwPriorityClass;

  // Take a snapshot of all processes in the system.
  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
  if( hProcessSnap == INVALID_HANDLE_VALUE )
  {
    printError( "CreateToolhelp32Snapshot (of processes)" );
    return( FALSE );
  }

  // Set the size of the structure before using it.
  pe32.dwSize = sizeof( PROCESSENTRY32 );

  // Retrieve information about the first process,
  // and exit if unsuccessful
  if( !Process32First( hProcessSnap, &pe32 ) )
  {
    printError( "Process32First" ); // Show cause of failure
    CloseHandle( hProcessSnap );    // Must clean up the
                                    //   snapshot object!
    return( FALSE );
  }

  // Now walk the snapshot of processes, and
  // display information about each process in turn
  do
  {
    printf( "\n\n"
      "=====================================================" );
    printf( "\nPROCESS NAME:  %s", pe32.szExeFile );
    printf( "\n"
      "-----------------------------------------------------" );

    // Retrieve the priority class.
    dwPriorityClass = 0;
    hProcess = OpenProcess(
      PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );
    if( hProcess == NULL )
      printError( "OpenProcess" );
    else
    {
      dwPriorityClass = GetPriorityClass( hProcess );
      if( !dwPriorityClass )
        printError( "GetPriorityClass" );
      CloseHandle( hProcess );
    }

    printf( "\n  process ID        = 0x%08X", pe32.th32ProcessID );
    printf( "\n  thread count      = %d",   pe32.cntThreads );
    printf( "\n  parent process ID = 0x%08X",
      pe32.th32ParentProcessID );
    printf( "\n  Priority Base     = %d", pe32.pcPriClassBase );
    if( dwPriorityClass )
      printf( "\n  Priority Class    = %d", dwPriorityClass );

    // List the modules and threads associated with this process
    ListProcessModules( pe32.th32ProcessID );
    ListProcessThreads( pe32.th32ProcessID );

  } while( Process32Next( hProcessSnap, &pe32 ) );

  CloseHandle( hProcessSnap );
  return( TRUE );
}


BOOL ListProcessModules( DWORD dwPID )
{
  HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
  MODULEENTRY32 me32;

  // Take a snapshot of all modules in the specified process.
  hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );
  if( hModuleSnap == INVALID_HANDLE_VALUE )
  {
    printError( "CreateToolhelp32Snapshot (of modules)" );
    return( FALSE );
  }

  // Set the size of the structure before using it.
  me32.dwSize = sizeof( MODULEENTRY32 );

  // Retrieve information about the first module,
  // and exit if unsuccessful
  if( !Module32First( hModuleSnap, &me32 ) )
  {
    printError( "Module32First" ); // Show cause of failure
    CloseHandle( hModuleSnap );    // Must clean up the
                                   //   snapshot object!
    return( FALSE );
  }

  // Now walk the module list of the process,
  // and display information about each module
  do
  {
    printf( "\n\n     MODULE NAME:     %s",
      me32.szModule );
    printf( "\n     executable     = %s",
      me32.szExePath );
    printf( "\n     process ID     = 0x%08X",
      me32.th32ProcessID );
    printf( "\n     ref count (g)  =     0x%04X",
      me32.GlblcntUsage );
    printf( "\n     ref count (p)  =     0x%04X",
      me32.ProccntUsage );
    printf( "\n     base address   = 0x%08X",
      (DWORD) me32.modBaseAddr );
    printf( "\n     base size      = %d",
      me32.modBaseSize );

  } while( Module32Next( hModuleSnap, &me32 ) );

  CloseHandle( hModuleSnap );
  return( TRUE );
}

BOOL ListProcessThreads( DWORD dwOwnerPID ) 
{ 
  HANDLE hThreadSnap = INVALID_HANDLE_VALUE; 
  THREADENTRY32 te32; 
 
  // Take a snapshot of all running threads  
  hThreadSnap = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ); 
  if( hThreadSnap == INVALID_HANDLE_VALUE ) 
    return( FALSE ); 
 
  // Fill in the size of the structure before using it. 
  te32.dwSize = sizeof(THREADENTRY32 ); 
 
  // Retrieve information about the first thread,
  // and exit if unsuccessful
  if( !Thread32First( hThreadSnap, &te32 ) ) 
  {
    printError( "Thread32First" ); // Show cause of failure
    CloseHandle( hThreadSnap );    // Must clean up the
                                   //   snapshot object!
    return( FALSE );
  }

  // Now walk the thread list of the system,
  // and display information about each thread
  // associated with the specified process
  do 
  { 
    if( te32.th32OwnerProcessID == dwOwnerPID )
    {
      printf( "\n\n     THREAD ID      = 0x%08X",
        te32.th32ThreadID ); 
      printf( "\n     base priority  = %d", te32.tpBasePri ); 
      printf( "\n     delta priority = %d", te32.tpDeltaPri ); 
    }
  } while( Thread32Next(hThreadSnap, &te32 ) ); 

  CloseHandle( hThreadSnap );
  return( TRUE );
}

void printError( TCHAR* msg )
{
  DWORD eNum;
  TCHAR sysMsg[256];
  TCHAR* p;

  eNum = GetLastError( );
  FormatMessage(
         FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
         NULL, eNum,
         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang.
         sysMsg, 256, NULL );

  // Trim the end of the line and terminate it with a null
  p = sysMsg;
  while( ( *p > 31 ) || ( *p == 9 ) )
    ++p;
  do { *p-- = 0; } while( ( p >= sysMsg ) &&
                          ( ( *p == '.' ) || ( *p < 33 ) ) );

  // Display the message
  printf( "\n  WARNING: %s failed with error %d (%s)",
    msg, eNum, sysMsg );
}


See Also
Snapshots of the System



Send comments about this topic to Microsoft 

Build date: 8/15/2007
赵4老师 2014-11-21
  • 打赏
  • 举报
回复
CreateToolhelp32Snapshot Function Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these processes. HANDLE WINAPI CreateToolhelp32Snapshot( __in DWORD dwFlags, __in DWORD th32ProcessID ); Parameters dwFlags The portions of the system to be included in the snapshot. This parameter can be one or more of the following values. Value Meaning TH32CS_INHERIT 0x80000000 Indicates that the snapshot handle is to be inheritable. TH32CS_SNAPALL Includes all processes and threads in the system, plus the heaps and modules of the process specified in th32ProcessID. Equivalent to specifying the TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE, TH32CS_SNAPPROCESS, and TH32CS_SNAPTHREAD values combined using an OR operation ('|'). TH32CS_SNAPHEAPLIST 0x00000001 Includes all heaps of the process specified in th32ProcessID in the snapshot. To enumerate the heaps, see Heap32ListFirst. TH32CS_SNAPMODULE 0x00000008 Includes all modules of the process specified in th32ProcessID in the snapshot. To enumerate the modules, see Module32First. 64-bit Windows: Using this flag in a 32-bit application includes 32-bit modules, while using it in a 64-bit application includes 64-bit modules. TH32CS_SNAPMODULE32 0x00000010 Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when run on 64-bit Windows. This flag can be combined with TH32CS_SNAPMODULE or TH32CS_SNAPALL. TH32CS_SNAPPROCESS 0x00000002 Includes all processes in the system in the snapshot. To enumerate the processes, see Process32First. TH32CS_SNAPTHREAD 0x00000004 Includes all threads in the system in the snapshot. To enumerate the threads, see Thread32First. To identify the threads that belong to a specific process, compare its process identifier to the th32OwnerProcessID member of the THREADENTRY32 structure when enumerating the threads. th32ProcessID The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate the current process. This parameter is used when the TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, or TH32CS_SNAPALL value is specified. Otherwise, it is ignored and all processes are included in the snapshot. If the specified process is a 64-bit process and the caller is a 32-bit process, this call will fail. Note that you can use the QueryFullProcessImageName function to retrieve the full name of an executable image for both 32- and 64-bit processes from a 32-bit process. Return Value If the function succeeds, it returns an open handle to the specified snapshot. If the function fails, it returns INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. Remarks The snapshot taken by this function is examined by the other tool help functions to provide their results. Access to the snapshot is read only. The snapshot handle acts as an object handle and is subject to the same rules regarding which processes and threads it is valid in. To enumerate the heap or module states for all processes, specify TH32CS_SNAPALL and set th32ProcessID to zero. Then, for each additional process in the snapshot, call CreateToolhelp32Snapshot again, specifying its process identifier and the TH32CS_SNAPHEAPLIST or TH32_SNAPMODULE value. To destroy the snapshot, use the CloseHandle function. Example Code For an example, see Taking a Snapshot and Viewing Processes. Requirements Client Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows Me, Windows 98, or Windows 95. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Tlhelp32.h. Library Use Kernel32.lib. DLL Requires Kernel32.dll. See Also CloseHandle Heap32ListFirst Module32First Process32First Snapshots of the System Thread32First Tool Help Functions Send comments about this topic to Microsoft Build date: 8/15/2007

65,183

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧