枚举WINDOWS中进程需要使用OpenProcess,EnumProcessModules,GetModuleBaseName,EnumProcesses函数,
而创建线程用的是CreateThread函数。
对进程的枚举实例在MSDN中有,搜索EnumProcesses函数就会找到链接,
需要添加papi.h库文件,编译器链接加入Psapi.lib库(Psapi.dll)
线程的创建比较简单,其中ThreadAPI2使用SuspendThread(hThread1),ResumeThread(hThread1)方法来对线程1进行挂起和唤醒。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "psapi.h"
HANDLE hThread1,hThread2;
DWORD WINAPI ThreadAPI(PVOID pvParam)
{
DWORD m_Count = 0;
TCHAR ThreadName[MAX_PATH] = TEXT("First Thread :");
while(m_Count < 600)
{
m_Count++;
_tprintf( TEXT("%s (PID: %u)/n"), ThreadName, m_Count );
}
wprintf( TEXT("%s /n"), TEXT("END OF THREADAPI1"));
return m_Count;
}
DWORD WINAPI ThreadAPI2(PVOID pvParam)
{
DWORD m_Count = 0;
TCHAR ThreadName[MAX_PATH] = TEXT("Second Thread :");
while(m_Count < 650)
{
m_Count++;
_tprintf( TEXT("%s (PID: %u)/n"), ThreadName, m_Count );
if( m_Count == 500)
{
wprintf( TEXT("%s /n"), TEXT("SuspentThread : First Thread"));
SuspendThread(hThread1);
}
if( m_Count == 600)
{
wprintf( TEXT("%s /n"), TEXT("ResumeThread : First Thread"));
ResumeThread(hThread1);
}
}
wprintf( TEXT("%s /n"), TEXT("END OF THREADAPI2"));
return m_Count;
}
void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Print the process name and identifier.
_tprintf( TEXT("%s (PID: %u)/n"), szProcessName, processID );
CloseHandle( hProcess );
}
void main( )
{
// Get the list of process identifiers.
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
/*
BOOL EnumProcesses(
DWORD* pProcessIds,
DWORD cb,
DWORD* pBytesReturned
);
*/
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
_tprintf( TEXT("cProcesses = %d /n"), cProcesses );
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
{
PrintProcessNameAndID( aProcesses[i] );
}
/*
DWORD dwThreadID;
hThread1 = CreateThread(NULL,
NULL,
ThreadAPI,
NULL,
NULL,
&dwThreadID);
hThread2 = CreateThread(NULL,
NULL,
ThreadAPI2,
NULL,
NULL,
NULL);
*/
getchar();
}