1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
|
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::match_wild_err_arm)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::ignored_unit_patterns)]
#![allow(clippy::for_kv_map)]
#![allow(clippy::double_ended_iterator_last)]
#![allow(clippy::single_match_else)]
//! Process Supervisor Example
//!
//! Demonstrates how to use Fork with Hash to build a simple process supervisor
//! that tracks multiple child processes and gets notified when they exit.
//!
//! Run with: cargo run --example supervisor
use std::{
collections::HashMap,
process::{Command, exit},
time::{Duration, Instant},
};
use fork::{Fork, fork, waitpid};
#[derive(Debug)]
struct ProcessInfo {
name: String,
started_at: Instant,
restarts: u32,
}
fn main() {
println!("š Starting Process Supervisor\n");
// HashMap using Fork as the key!
let mut supervised: HashMap<Fork, ProcessInfo> = HashMap::new();
// Spawn 3 worker processes
for i in 1..=3 {
match spawn_worker(i, &mut supervised) {
Ok(_) => println!("ā
Worker {} spawned", i),
Err(e) => eprintln!("ā Failed to spawn worker {}: {}", i, e),
}
}
println!("\nš Supervisor managing {} processes\n", supervised.len());
// Supervisor loop - wait for children to exit
loop {
if supervised.is_empty() {
println!("ā
All workers completed. Supervisor exiting.");
break;
}
// Check each supervised process
let mut exited = Vec::new();
for (fork_result, info) in &supervised {
if let Some(pid) = fork_result.child_pid() {
// Try non-blocking wait to see if process exited
// Note: In real code, you'd use WNOHANG with waitpid
// For this example, we'll simulate with a simple check
println!("ā³ Checking worker '{}' (PID: {})", info.name, pid);
}
}
// In a real supervisor, you'd use signal handlers (SIGCHLD)
// or non-blocking waitpid with WNOHANG to detect exits
// For this demo, we'll wait for any child
std::thread::sleep(Duration::from_millis(500));
// Simple approach: try to find which child exited
// In production, use SIGCHLD signal handler
for (fork_result, _info) in &supervised {
if let Some(pid) = fork_result.child_pid() {
// Check if this specific child exited (blocking wait)
// In real code, use waitpid with WNOHANG
match waitpid(pid) {
Ok(_) => {
exited.push(*fork_result);
}
Err(_) => {
// Process still running or error
}
}
}
}
// Handle exited processes
for fork_result in exited {
if let Some(info) = supervised.remove(&fork_result) {
let pid = fork_result.child_pid().unwrap();
let uptime = info.started_at.elapsed();
println!(
"\nš Worker '{}' (PID: {}) exited after {:.2}s",
info.name,
pid,
uptime.as_secs_f64()
);
// Optional: Restart the worker
if info.restarts < 3 {
println!("š Restarting worker '{}'...", info.name);
let worker_num: u32 = info
.name
.split('-')
.last()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
match restart_worker(worker_num, &mut supervised, info.restarts + 1) {
Ok(_) => println!("ā
Worker '{}' restarted", info.name),
Err(e) => eprintln!("ā Failed to restart: {}", e),
}
} else {
println!(
"ā ļø Worker '{}' reached max restarts, not restarting",
info.name
);
}
}
}
}
}
fn spawn_worker(id: u32, supervised: &mut HashMap<Fork, ProcessInfo>) -> std::io::Result<()> {
match fork()? {
result @ Fork::Parent(_) => {
// Store in HashMap using Fork as key!
supervised.insert(
result,
ProcessInfo {
name: format!("worker-{}", id),
started_at: Instant::now(),
restarts: 0,
},
);
Ok(())
}
Fork::Child => {
// Worker process - simulate some work
println!("š· Worker {} starting work...", id);
// Simulate different work durations
Command::new("sleep")
.arg(format!("{}", id))
.status()
.expect("Failed to execute sleep");
println!("ā
Worker {} completed", id);
exit(0);
}
}
}
fn restart_worker(
id: u32,
supervised: &mut HashMap<Fork, ProcessInfo>,
restart_count: u32,
) -> std::io::Result<()> {
match fork()? {
result @ Fork::Parent(_) => {
supervised.insert(
result,
ProcessInfo {
name: format!("worker-{}", id),
started_at: Instant::now(),
restarts: restart_count,
},
);
Ok(())
}
Fork::Child => {
println!(
"š· Worker {} (restart #{}) starting work...",
id, restart_count
);
Command::new("sleep")
.arg("1")
.status()
.expect("Failed to execute sleep");
println!("ā
Worker {} (restart #{}) completed", id, restart_count);
exit(0);
}
}
}
|