在windows VC++下得到父进程ID的方法,求····
请教,我在从linux移植code到windows上时,有得到子进程和父进程id的函数:getpid(),getppid(),在VC++上子进程的id可以直接用getpid()得到,但是父进程没有对应getppid()的函数,我该如何实现呢,急等~~望各位大侠帮忙······
[解决办法]
- C/C++ code
#include <windows.h>#include <tchar.h>#include <stdio.h>#include <psapi.h>void PrintModules( DWORD processID ){ HMODULE hMods[1024]; HANDLE hProcess; DWORD cbNeeded; unsigned int i; // Print the process identifier. printf( "\nProcess ID: %u\n", processID ); // Get a list of all the modules in this process. hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID ); if (NULL == hProcess) return; if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ ) { TCHAR szModName[MAX_PATH]; // Get the full path to the module's file. if ( GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName)/sizeof(TCHAR))) { // Print the module name and handle value. _tprintf(TEXT("\t%s (0x%08X)\n"), szModName, hMods[i]); } } } CloseHandle( hProcess );}void main( ){ // Get the list of process identifiers. DWORD aProcesses[1024], cbNeeded, cProcesses; unsigned int i; if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return; // Calculate how many process identifiers were returned. cProcesses = cbNeeded / sizeof(DWORD); // Print the name of the modules for each process. for ( i = 0; i < cProcesses; i++ ) PrintModules( aProcesses[i] );}
[解决办法]
windows下子进程跟父进程之间的关系本事就是没什么关联的,不像Linux,windows也没有直接一个API可以得到父进程的ID,可以参考 http://www.cnblogs.com/login007/archive/2011/09/02/2163468.html
[解决办法]
前段时间刚好用到
- C/C++ code
DWORD GetParentProcessID(DWORD dwProcessId) { LONG status; DWORD dwParentPID = (DWORD)-1; HANDLE hProcess; PROCESS_BASIC_INFORMATION pbi; PROCNTQSIP NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress( GetModuleHandle(L"ntdll"), "NtQueryInformationProcess"); if(NULL == NtQueryInformationProcess) { return (DWORD)-1; } // Get process handle hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE, dwProcessId); 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; }
[解决办法]