Debian Codegraph @

examples/supervisor.rs

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