注意: AssignProcessToJobObject仅适用于win32 desktop app, 比如notepad是适用的,calculator是不适用的
下面的demo是将notepad的句柄分配给作业,然后由TerminateJobObject统一kill
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<windows.h> using namespace std; bool ExecuteSoftware(HANDLE * hSoftwareJob, char * name, const int countExecute); void KillProcess(HANDLE hSoftwareJob); int main() { HANDLE notepadJob; const int SIZE_NOTE = 3; notepadJob = CreateJobObject(NULL, NULL); cout << "Execute WordPad\n"; if (!ExecuteSoftware(¬epadJob, const_cast<char*>("notepad.exe"), SIZE_NOTE)) { cout << "Can't execute all process\n"; Sleep(1500); } cout << "Killing groups\n"; KillProcess(notepadJob); Sleep(2500); return 0; } bool ExecuteSoftware(HANDLE * hSoftwareJob, char * name, const int countExecute) { STARTUPINFO si; LPTSTR lpszSystemInfo; PROCESS_INFORMATION pi; TCHAR tchBuff[MAX_PATH + 1]; lpszSystemInfo = tchBuff; GetSystemDirectory(lpszSystemInfo, MAX_PATH + 1); wsprintf(tchBuff, "%s\\%s", lpszSystemInfo, name); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); for (int i = 0; i < countExecute; i++) { if (!CreateProcess(NULL, tchBuff, NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &si, &pi)) //CREATE_BREAKAWAY_FROM_JOB是必需的 { return false; } else { AssignProcessToJobObject(*hSoftwareJob, pi.hProcess); int err = GetLastError(); } } return true; } void KillProcess(HANDLE hSoftwareJob) { TerminateJobObject(hSoftwareJob, 0); int err = GetLastError(); }
有意思的是如果使用openprocess获取计算器的句柄,然后将句柄传递给AssignProcessToJobObject,同样也可以被TerminateJobObject杀掉进程。
不过测试之后发现createprocess得到的processid与任务管理器中看到的pid不一样,也就是如果createprocess得到的Pid传给openprocess之后,获取的新句柄将无法使用。