// ParentPid.cpp : Defines the entry point for the console application.
// 对着你的项目点击右键,依次选择:属性、配置属性、常规,然后右边有个“项目默认值”,下面有个2个MFC的使用选项
#include "stdafx.h"
#include <afx.h>
#include <Psapi.h>
#include <Windows.h>
#pragma comment (lib, "Psapi.lib")
#define MAX_PROCESS_LENGTH (128)
// 获取进程名称
bool GetProcessName(DWORD processid,LPTSTR buf,int len)
{
//make sure buf is valid and long enough
buf[0]=0;
if(processid ==8)
{
_tcscpy(buf, L"System");
return true;
}
if(processid==0)
{
_tcscpy(buf, L"System Idle Process");
return true;
}
HANDLE hProcess =OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,false,processid);
if(hProcess == NULL)
{
_tcscpy(buf, L"unknown(OpenProcess error)");
return false;
}
HMODULE hModule;
DWORD cbReturned;
BOOL bret = EnumProcessModules(hProcess ,&hModule, sizeof(hModule), &cbReturned );
if(bret)
GetModuleBaseName(hProcess,hModule,buf,len);
else{
_tcscpy(buf, L"unknown(GetModuleBaseName error)");
}
CloseHandle( hProcess ) ;
return bret;
}
// 获取父进程ID
ULONG_PTR GetParentProcessId(int pid)
{
ULONG_PTR pbi[6];
ULONG ulSize = 0;
LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
*(FARPROC *)&NtQueryInformationProcess =
GetProcAddress(LoadLibraryA( "NTDLL.DLL"), "NtQueryInformationProcess" );
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if(NtQueryInformationProcess){
if(NtQueryInformationProcess(hProcess, 0,
&pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
return pbi[5];
}
return (ULONG_PTR)-1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int row = 1;
if(argc <= 1) {
wprintf(_T("%d) parameter error.\n"), row);
return -1;
}
CString str = argv[1];
int pid = _ttoi(str);
CString strPrint;
ULONG_PTR ppid;
LPTSTR pName = (LPTSTR)malloc( sizeof(_TCHAR) * MAX_PROCESS_LENGTH );
for(; ; row++){
ppid = GetParentProcessId( pid );
if(-1 == ppid ) {
wprintf(_T("%d) No parent process.\n"), row);
break;
}
if(!GetProcessName(ppid, pName, MAX_PROCESS_LENGTH)){
wprintf(_T("%d) No parent process.\n"), row);
break;
}
strPrint.Format(_T("%d) Pid[%d]'s parent is [%d][%s]."), row, pid, ppid, pName);
wprintf(_T("%s\n"), strPrint.GetBuffer() );
pid = ppid;
}
return 0;
}
WIN通过子进程获取父进程ID
最新推荐文章于 2024-03-08 18:03:07 发布