sal/rhaiexamples/03_process_management.rhai
2025-04-04 18:21:16 +02:00

64 lines
2.3 KiB
Plaintext

// 03_process_management.rhai
// Demonstrates process management operations using SAL
// Check if common commands exist
println("Checking if common commands exist:");
let commands = ["ls", "echo", "cat", "grep"];
for cmd in commands {
let exists = which(cmd);
println(` - ${cmd}: ${exists}`);
}
// Run a simple command
println("\nRunning a simple echo command:");
let echo_result = run_command("echo 'Hello from Rhai process management!'");
println(`Command output: ${echo_result.stdout}`);
// The CommandResult type doesn't have an exit_code property
println(`Success: ${echo_result.success}`);
// Run a command silently (no output to console)
println("\nRunning a command silently:");
let silent_result = run_silent("ls -la");
println(`Command success: ${silent_result.success}`);
println(`Command output length: ${silent_result.stdout.len()} characters`);
// Create custom run options
println("\nRunning a command with custom options:");
let options = new_run_options();
options["die"] = false; // Don't return error if command fails
options["silent"] = true; // Suppress output to stdout/stderr
options["async_exec"] = false; // Run synchronously
options["log"] = true; // Log command execution
let custom_result = run("echo 'Custom options test'", options);
println(`Command success: ${custom_result.success}`);
println(`Command output: ${custom_result.stdout}`);
// List processes
println("\nListing processes (limited to 5):");
let processes = process_list("");
let count = 0;
for proc in processes {
if count >= 5 {
break;
}
// Just print the PID since we're not sure what other properties are available
println(` - PID: ${proc.pid}`);
count += 1;
}
println(`Total processes: ${processes.len()}`);
// Run a command that will create a background process
// Note: This is just for demonstration, the process will be short-lived
println("\nRunning a background process:");
let bg_options = new_run_options();
bg_options["async_exec"] = true;
// Fix the command to avoid issues with shell interpretation
let bg_result = run("sleep 1", bg_options);
println("Background process started");
// Wait a moment to let the background process run
run_command("sleep 0.5");
println("Main script continuing while background process runs");
"Process management script completed successfully!"