From 6d63ee291ca86deb74f5eb7ab603649d0ae74df1 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Sat, 19 Aug 2023 19:58:15 +0100 Subject: [PATCH] Add thread for watching child process --- src/main.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2437bff..04515bc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,10 +3,10 @@ use std::env; use std::fs::remove_file; use std::io::{BufRead, BufReader, Write}; use std::os::unix::net::{UnixListener, UnixStream}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::process::Command; use std::thread; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; const ENV_VAR: &str = "IPC_SOCK_PATH"; @@ -41,10 +41,6 @@ impl SocketServer { } } } - - fn path(&self) -> &Path { - &self.socket_path - } } impl Drop for SocketServer { @@ -81,16 +77,30 @@ fn client(path: String) { stream.write_all(b"Hello World").unwrap(); } +fn monitor_child(socket_path: PathBuf) { + loop { + println!("Starting child process"); + let mut child_proc = Command::new(env::current_exe().unwrap()) + .env(ENV_VAR, &socket_path) + .spawn() + .unwrap(); + + child_proc.wait().unwrap(); + + println!("Child process died"); + + thread::sleep(Duration::from_secs(5)); + } +} + fn main() { if let Ok(path) = env::var(ENV_VAR) { client(path); } else { let server = SocketServer::new(); - let _child = Command::new(env::current_exe().unwrap()) - .env(ENV_VAR, server.path()) - .spawn() - .unwrap(); + let socket_path = server.socket_path.clone(); + thread::spawn(|| monitor_child(socket_path)); server.run(); }