1.Windows提供了一个作业(job )内核对象,它允许你将进程组合在一起并创建一个“沙箱”来 限制进程能够做什么。最好将作业对象想象成一个进程容器。但是,即使作业中只包含一个进程,也是非常有用的,因为这样可以对进程施加平时不能施加的限制。
#include <string>
#include <windows.h>
#include <tchar.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//询问一下当前进程是否已在作业中
BOOL bInJob;
IsProcessInJob(GetCurrentProcess(), NULL, &bInJob);
if(bInJob)
{
wcout << TEXT("currecnt process is already in Job!") << endl;
system("PAUSE");
return 0;
}
//为作业设一些安全限制,可设置的条件相当之多和复杂
JOBOBJECT_BASIC_LIMIT_INFORMATION jbli = {0};
jbli.PriorityClass = IDLE_PRIORITY_CLASS;
jbli.PerJobUserTimeLimit.QuadPart = 1000;
JOBOBJECT_BASIC_UI_RESTRICTIONS jbur;
jbur.UIRestrictionsClass = JOB_OBJECT_UILIMIT_NONE|
JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_HANDLES;
//创建一个作业
HANDLE hJob = CreateJobObject(NULL, TEXT("SomeJob"));
//把安全限制和作业关联起来
SetInformationJobObject(hJob, JobObjectBasicLimitInformation, &jbli, sizeof(jbli));
SetInformationJobObject(hJob, JobObjectBasicUIRestrictions, &jbur, sizeof(jbur));
//创建进程,并把之加入作业中
STARTUPINFO si = {sizeof(si)};
PROCESS_INFORMATION pi;
TCHAR cmd[] = TEXT("NOTEPAD");
if( CreateProcess(NULL, cmd, NULL, NULL, FALSE,
CREATE_SUSPENDED | CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi) )
{
AssignProcessToJobObject(hJob, pi.hProcess);
ResumeThread(pi.hThread);
CloseHandle(pi.hThread);
//等待作业或进程结束,再进行统计
HANDLE hdls[] = { pi.hProcess, hJob };
DWORD dwCondition = WaitForMultipleObjects(sizeof(hdls) / sizeof(HANDLE), hdls, FALSE, INFINITE);
switch(dwCondition - WAIT_OBJECT_0)
{
case 0:
//do something here
break;
case 1:
//do something here
break;
}
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
GetProcessTimes(pi.hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime);
wcout << TEXT("Kernel = ") << KernelTime.dwLowDateTime / 1000 << " and User = "
<< UserTime.dwLowDateTime / 10000 << endl;
CloseHandle(pi.hProcess);
}
CloseHandle(hJob);
system("PAUSE");
return 0;
}
2. 创建好一个作业之后,接着一般需要限制作业中的进程能做的事情;换言之,现在要设置 一个“沙箱”。