- 윈도우 API 테스트
- windows API로 프로세스의 정보 받아오기 (원본)
~cpp
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <Windows.h>
#include <TlHelp32.h>
void killProcess(TCHAR*);
int _tmain(int argc, TCHAR *argv[]){
// snap every current process
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hProcessSnap == INVALID_HANDLE_VALUE) {
_tprintf(_T("CreateToolhelp32Snapshot erre\n"));
exit(EXIT_FAILURE);
}
// structure to hold process's inform
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
// Process32First :: get the first process snapshot
if(!Process32First(hProcessSnap, &pe32)){
_tprintf(_T("Process32First error!\n"));
CloseHandle(hProcessSnap);
exit(EXIT_FAILURE);
}
_tprintf(_T("\t[Process name]\t[PID]\t[ThreadID]\t[PPID]\n"));
int countProcess=0;
do{
countProcess += 1;
_tprintf(_T("%25s %8d %8d %8d\n"),
pe32.szExeFile, pe32.th32ProcessID, pe32.cntThreads, pe32.th32ParentProcessID);
}while(Process32Next(hProcessSnap, &pe32));
printf("number of process = %d", countProcess);
return 0;
}
~cpp
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <Windows.h>
#include <TlHelp32.h>
void killProcess(TCHAR*);
int _tmain(int argc, TCHAR *argv[]){
// kill process
TCHAR *targetProcess = _T("NateOnMain.exe"); // 종료하려는 프로세스의 이름을 쓴다
killProcess(targetProcess);
return 0;
}
// Works fine
void killProcess(TCHAR *target){
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hProcess = NULL;
do{
if(0 == _tcscmp(pe32.szExeFile, target)){
// get the process handle
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
if(hProcess){
// kill it
TerminateProcess(hProcess, -1);
CloseHandle(hProcess);
printf("종료 성공!");
break;
}
}
}while(Process32Next(hProcessSnap, &pe32));
CloseHandle(hProcessSnap);
}