日期:2014-05-17 浏览次数:20834 次
#include "stdafx.h" void StartRestrictedProcess() { //检查当前进程是否处于作业中 BOOL bInJob = FALSE; IsProcessInJob(GetCurrentProcess(), NULL, &bInJob); if (bInJob) { MessageBox(NULL, _T("当前进程已经在作业中"), NULL,MB_ICONINFORMATION | MB_OK); return; } //创建作业对象 HANDLE hJob = CreateJobObject(NULL, _T("RestrictedProcessJob")); //限制条件1 JOBOBJECT_BASIC_LIMIT_INFORMATION jobli = { 0 }; jobli.PriorityClass = IDLE_PRIORITY_CLASS; jobli.PerJobUserTimeLimit.QuadPart = 10000; jobli.LimitFlags = JOB_OBJECT_LIMIT_PRIORITY_CLASS | JOB_OBJECT_LIMIT_JOB_TIME; SetInformationJobObject(hJob, JobObjectBasicLimitInformation, &jobli, sizeof(jobli)); //2 JOBOBJECT_BASIC_UI_RESTRICTIONS jobuir; //dword jobuir.UIRestrictionsClass = JOB_OBJECT_UILIMIT_NONE; //没有限制 jobuir.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_EXITWINDOWS; jobuir.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES; SetInformationJobObject(hJob, JobObjectBasicUIRestrictions, &jobuir, sizeof(jobuir)); //创建子进程 STARTUPINFO si = {sizeof(si)}; PROCESS_INFORMATION pi; TCHAR szExe[] = _T("D:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\Tools\\spyxx.exe"); CreateProcess(NULL, szExe, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); //与作业关联 AssignProcessToJobObject(hJob, pi.hProcess); ResumeThread(pi.hThread); CloseHandle(pi.hThread); //等待子进程返回 HANDLE h[2]; h[0] = pi.hProcess; h[1] = hJob; DWORD dw = WaitForMultipleObjects(2, h, FALSE, INFINITE); switch (dw - WAIT_OBJECT_0) { case 0: //子进程结束返回 break; case 1: //时间用完 break; } //获取进程相关的一些时间信息 FILETIME CreateTime; FILETIME ExitTime; FILETIME KernelTime; FILETIME UserTime; GetProcessTimes(pi.hProcess, &CreateTime, &ExitTime, &KernelTime, &UserTime); TCHAR szInfo[MAX_PATH]; StringCchPrintf(szInfo, MAX_PATH, _T("Kernel = %u | User = %u\n"), KernelTime.dwLowDateTime / 10000, UserTime.dwLowDateTime / 10000); MessageBox(GetActiveWindow(), szInfo, NULL, MB_OK | MB_ICONINFORMATION); //关闭句柄 CloseHandle(hJob); CloseHandle(pi.hProcess); } int _tmain(int argc, _TCHAR* argv[]) { StartRestrictedProcess(); return 0; }