Posted on 2005-10-22 11:01
Tommy Liang 阅读(1708)
评论(0) 编辑 收藏 引用 所属分类:
进程与线程
如下:
// ProcessHelper.h: interface for the ProcessHelper class.
//

/**///////////////////////////////////////////////////////////////////////
#if !defined(AFX_PROCESSHELPER_H__EA2A87A6_5E54_4610_8EDD_C5F8119D2976__INCLUDED_)
#define AFX_PROCESSHELPER_H__EA2A87A6_5E54_4610_8EDD_C5F8119D2976__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <Tlhelp32.h>
#include <Psapi.h>

#define ProcessBasicInformation 0

typedef struct


{
DWORD ExitStatus;
DWORD PebBaseAddress;
DWORD AffinityMask;
DWORD BasePriority;
ULONG UniqueProcessId;
ULONG InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION;

// ntdll!NtQueryInformationProcess (NT specific!)
//
// The function copies the process information of the
// specified type into a buffer
//
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQueryInformationProcess(
// IN HANDLE ProcessHandle, // handle to process
// IN PROCESSINFOCLASS InformationClass, // information type
// OUT PVOID ProcessInformation, // pointer to buffer
// IN ULONG ProcessInformationLength, // buffer size in bytes
// OUT PULONG ReturnLength OPTIONAL // pointer to a 32-bit
// // variable that receives
// // the number of bytes
// // written to the buffer
// );
typedef LONG (WINAPI *PROCNTQSIP)(HANDLE,UINT,PVOID,ULONG,PULONG);

class ProcessHelper


{
public:
ProcessHelper();
virtual ~ProcessHelper();

DWORD GetParentProcessID(DWORD dwId);

DWORD GetProcessFileName( DWORD dwId,LPTSTR lpImageFileName);

private:
PROCNTQSIP NtQueryInformationProcess;


};


ProcessHelper::ProcessHelper()


{
NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress(
GetModuleHandle("ntdll"),
"NtQueryInformationProcess"
);
}

ProcessHelper::~ProcessHelper()


{
}

DWORD ProcessHelper::GetProcessFileName( DWORD dwId,LPTSTR lpImageFileName)


{
HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,dwId);
if (hSnapshot == INVALID_HANDLE_VALUE)
return (FALSE);


MODULEENTRY32 me32 =
{0};
me32.dwSize = sizeof(MODULEENTRY32);

if(! Module32First(hSnapshot,&me32))

{
CloseHandle(hSnapshot);
return (DWORD) -1;
}

strcpy(lpImageFileName,me32.szModule);

CloseHandle(hSnapshot);
return (DWORD)0;
}

DWORD ProcessHelper::GetParentProcessID(DWORD dwId)


{
if (!NtQueryInformationProcess) return -1;
LONG status;
DWORD dwParentPID = (DWORD)-1;
HANDLE hProcess;
PROCESS_BASIC_INFORMATION pbi;
// Get process handle
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,dwId);
if (!hProcess)
return (DWORD)-1;
// Retrieve information
status = NtQueryInformationProcess( hProcess,
ProcessBasicInformation,
(PVOID)&pbi,
sizeof(PROCESS_BASIC_INFORMATION),
NULL
);
// Copy parent Id on success
if (!status)
dwParentPID = pbi.InheritedFromUniqueProcessId;
CloseHandle (hProcess);
return dwParentPID;
}


#endif