先上代码吧
有不懂得可以提问啊!
#include <iostream> #include <vector> #include <map> #include <Windows.h> #include <tchar.h> #include <process.h> #include <Strsafe.h> void CreateProcessInJob(PTSTR sCommangline, HANDLE hJob) { STARTUPINFO stInfo = {sizeof(stInfo)}; PROCESS_INFORMATION process_info = {0}; int len = _tcsclen(sCommangline) * sizeof(TCHAR); int lSize = len + sizeof(TCHAR); PTSTR pBuffer = new TCHAR[lSize]; memset(pBuffer,0,lSize); // size 必须要加上NULL字符 StringCbCopy(pBuffer,lSize,sCommangline); // 参数2 的缓冲区要可写,访问违规 BOOL bOk = CreateProcess(NULL,pBuffer,NULL,NULL,FALSE,CREATE_BREAKAWAY_FROM_JOB|CREATE_SUSPENDED,NULL, NULL,&stInfo,&process_info); __try{ if(!bOk)__leave; AssignProcessToJobObject(hJob,process_info.hProcess); // 激活线程 ::ResumeThread(process_info.hThread); } __finally{ delete []pBuffer; pBuffer = NULL; //关闭进程对象,线程对象 CloseHandle(process_info.hProcess); CloseHandle(process_info.hThread); } } unsigned int WINAPI ThreadFunc(LPVOID lparam) { HANDLE hIOCP = (HANDLE)lparam; BOOL bGoOn = TRUE; DWORD dwlen = 0; DWORD dwProcessID; ULONG_PTR comkey; LPOVERLAPPED ov; while(bGoOn && GetQueuedCompletionStatus(hIOCP,&dwlen,&comkey,&ov,INFINITE)) { if (comkey == 1) { switch (dwlen) { case JOB_OBJECT_MSG_EXIT_PROCESS: dwProcessID = (DWORD)ov; printf("process ID %d\n",dwProcessID); break; case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: printf("over all"); ov; bGoOn = FALSE; break; case JOB_OBJECT_MSG_NEW_PROCESS: printf("new process ID %d\n",(DWORD)ov); break; } } } return 0; } int main( ) { // Get the list of process identifiers. HANDLE hJob=NULL; HANDLE hIOPort = NULL; HANDLE hThread = NULL; ULONG_PTR completionKey = 1; // user-defined __try { hJob= CreateJobObject(NULL,TEXT("myJob")); if(NULL == hJob){ __leave; } JOBOBJECT_BASIC_UI_RESTRICTIONS tagUiRestrictions; tagUiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_NONE; tagUiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_HANDLES | JOB_OBJECT_UILIMIT_EXITWINDOWS; BOOL bOk = SetInformationJobObject(hJob,JobObjectBasicUIRestrictions,&tagUiRestrictions, sizeof(tagUiRestrictions)); if (!bOk){ __leave; } hIOPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL, completionKey, 0); if (hIOPort == NULL){ __leave; } JOBOBJECT_ASSOCIATE_COMPLETION_PORT tagAssCompletionPort; tagAssCompletionPort.CompletionKey = (PVOID)completionKey; tagAssCompletionPort.CompletionPort = hIOPort; bOk = SetInformationJobObject(hJob,JobObjectAssociateCompletionPortInformation, &tagAssCompletionPort,sizeof(tagAssCompletionPort)); if (!bOk) { __leave; } hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, hIOPort, 0, NULL); if (hThread == NULL) { __leave; } CreateProcessInJob (TEXT("C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\spyxx.exe"),hJob); CreateProcessInJob(TEXT("C:\\Users\\Administrator\\Desktop\\procexp.exe"),hJob); WaitForSingleObject(hThread, INFINITE); } __finally { CloseHandle(hJob); CloseHandle(hIOPort); CloseHandle(hThread); hIOPort = hIOPort = hThread = NULL; } system("pause"); return 0; }