有兩段代碼 代碼一是單獨寫成函數來調用的, 我把他們合成一個主函數的代碼 就出錯 好像是變量遞增的問題,我怎麼也想不通,麻煩大家了。
代碼一 別人寫的:
#include
#include
#include
#include
#pragma comment(lib,"Psapi.lib")
int FindModules( DWORD processID )
{
HMODULE hMods[1024];
HANDLE hProcess;
DWORD cbNeeded;
unsigned int i;
// Get a handle to the process.
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );
if (NULL == hProcess) return 1;
// Get a list of all the modules in this process.
if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
{
TCHAR szModName[MAX_PATH];
if (GetModuleBaseName(hProcess, hMods[i], szModName,sizeof(szModName) / sizeof(TCHAR)))
{
if(strcmp(szModName,"sfc.dll")==0)
{
printf("%s PID:%d\n",szModName,processID);
break;
}
}
}
}
CloseHandle( hProcess );
return 0;
}
int main( void )
{
DWORD aProcesses[1024];
DWORD cbNeeded;
unsigned int i;
// Get the list of process identifiers.
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return 1;
// Print the names of the modules for each process.
for ( i = 0; i < cbNeeded / sizeof(DWORD); i++ )
{
FindModules( aProcesses[i] );
}
return 0;
}
代碼2:我想合到一個函數中:
#include
#include
#include
#pragma comment(lib,"Psapi.lib")
int main( void )
{
DWORD aProcesses[1024];
DWORD cbNeeded;
unsigned int i;
HMODULE hMods[1024];
HANDLE hProcess;
DWORD cbNeeded2;
unsigned int ii;
// Get the list of process identifiers.
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return 1;
// Print the names of the modules for each process.
for ( i = 0; i < cbNeeded / sizeof(DWORD); i++ )
{
// 錯誤下面這句,分開些函數就沒問題 i都等於0,寫在一個函數裡 就不行了,就返回2,必須把i加1,跳過過pid為0才行.
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i+1] );//我直接用aProcesses[i]怎麼不行啊?
if (NULL == hProcess) return 2;
// Get a list of all the modules in this process.
if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded2))
{
for ( ii = 0; ii < (cbNeeded2 / sizeof(HMODULE)); ii++ )
{
TCHAR szModName[MAX_PATH];
if (GetModuleBaseName(hProcess, hMods[ii], szModName,sizeof(szModName) / sizeof(TCHAR)))
{
if(strcmp(szModName,"sfc.dll")==0)
{
printf("%s PID:%d\n",szModName,aProcesses[i+1]);
break;
}
}
}
CloseHandle( hProcess );
}
}
return 0;
}
基礎太差了 單獨寫成函數是循環來調用,遇到pid=0的雖然失敗 但循環下一個, 合寫在一個主函數的時候沒仔細看代碼 直接把上面的return 給挪下來了,這就出現了id寫成aProcesses[i] 會失敗返回 寫成aProcesses[i+1]就跳過pid=0了。或者把return 換成continue就ok了