4. 运行沙盒

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

同步运行

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

#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 通信时,此功能非常有用。以下代码段展示了此使用情形,如需查看更详细的示例,请参阅 crc4tool

#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();