stream_basic/
stream_basic.rs

1//! Example: Basic streaming output from sandboxed process
2//!
3//! This example demonstrates how to capture and stream stdout/stderr
4//! from a sandboxed process in real-time.
5
6use sandbox_rs::{SandboxBuilder, StreamChunk};
7use std::time::Duration;
8use tempfile::tempdir;
9
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    let mut final_exit_code = result.exit_code;
31    let mut final_signal = result.signal;
32
33    for chunk in stream.into_iter() {
34        match chunk {
35            StreamChunk::Stdout(line) => {
36                println!("[STDOUT] {}", line);
37            }
38            StreamChunk::Stderr(line) => {
39                eprintln!("[STDERR] {}", line);
40            }
41            StreamChunk::Exit { exit_code, signal } => {
42                println!("\nProcess exited with code: {}", exit_code);
43                if let Some(sig) = signal {
44                    println!("Killed by signal: {}", sig);
45                }
46                final_exit_code = exit_code;
47                final_signal = signal;
48            }
49        }
50    }
51
52    // Update result with the actual exit code from streaming
53    let mut result = result;
54    result.exit_code = final_exit_code;
55    result.signal = final_signal;
56
57    println!("\nExecution stats:");
58    println!("  Exit code: {}", result.exit_code);
59    println!("  Wall time: {} ms", result.wall_time_ms);
60    println!("  Memory peak: {} bytes", result.memory_peak);
61
62    // Check for seccomp errors and return error if found
63    result.check_seccomp_error()?;
64
65    Ok(())
66}