4. 运行沙盒

在前面的部分中,您介绍了沙盒化环境、政策、执行器和 Sandboxee。下一步是创建并运行 Sandbox2 对象。

同步运行

沙盒可以同步运行,因此会阻塞,直到得出结果。以下代码段演示了 Sandbox2 对象的实例化及其同步执行。如需查看更详细的示例,请参阅 static

#include "sandboxed_api/sandbox2/sandbox2.h"

sandbox2::Sandbox2 s2(std::move(executor), std::move(policy));
sandbox2::Result result = s2.Run();  // Synchronous
LOG(INFO) << "Result of sandbox execution: " << result.ToString();

异步运行

您也可以异步运行沙盒,因此在获得结果之前不会阻塞。例如,在与 Sandboxee 通信时,这非常有用。以下代码段演示了此用例,如需更详细的示例,请参阅 crc4工具

#include "sandboxed_api/sandbox2/sandbox2.h"

sandbox2::Sandbox2 s2(std::move(executor), std::move(policy));
if (s2.RunAsync()) {
  // Communicate with sandboxee, use s2.Kill() to kill it if needed
  // ...
}
Sandbox2::Result result = s2.AwaitResult();
LOG(INFO) << "Final execution status: " << result.ToString();