CreateProcess TerminateProcess 创建与终止进程 demo

来源:互联网 发布:linux kill -9怎么用 编辑:程序博客网 时间:2024/05/21 01:31


用CreateProcess启动MyEclipse,5秒后终止该进程。

IDE:VS2010

#include <iostream>#include <windows.h>#include <tlhelp32.h>using namespace std;bool killProcess(PROCESS_INFORMATION& processInfo){    DWORD processId = processInfo.dwProcessId;    PROCESSENTRY32 processEntry = {0};    processEntry.dwSize = sizeof(PROCESSENTRY32);//给系统内的所有进程拍一个快照    HANDLE handleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);   //遍历每个正在运行的进程    if( Process32First(handleSnap, &processEntry) ){        BOOL isContinue = TRUE;//终止子进程        do{            if( processEntry.th32ParentProcessID == processId ){                HANDLE hChildProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processEntry.th32ProcessID);                if( hChildProcess ){                    TerminateProcess(hChildProcess, 0);                    CloseHandle(hChildProcess);                }            }            isContinue = Process32Next(handleSnap, &processEntry);        }while( isContinue );                HANDLE hBaseProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);        if( hBaseProcess ){            TerminateProcess(hBaseProcess, 0);            CloseHandle(hBaseProcess);        }    }DWORD exitCode = 0;GetExitCodeProcess(processInfo.hProcess, &exitCode);cout<<"exitCode="<<exitCode<<endl;    if( exitCode == STILL_ACTIVE ){        return false;    }    return true;}int main(){STARTUPINFO si;PROCESS_INFORMATION pi;ZeroMemory( &pi, sizeof(pi) );ZeroMemory( &si, sizeof(si) );si.cb = sizeof(si);if( CreateProcess(NULL, "D:\\MyEclipse2014GA\\myeclipse.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) ){Sleep(5000);cout<<killProcess(pi)<<endl;;}else{cout<<"创建失败!"<<endl;HANDLE hProcess = GetCurrentProcess();TerminateProcess(hProcess,0);}return 0;}


0 0
原创粉丝点击