1
Fork 0

Add thread for watching child process

This commit is contained in:
Jake Howard 2023-08-19 19:58:15 +01:00
parent 1bed74a34e
commit 6d63ee291c
Signed by: jake
GPG Key ID: 57AFB45680EDD477
1 changed files with 20 additions and 10 deletions

View File

@ -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();
}