Skip to content

Instantly share code, notes, and snippets.

@dylanwh
Created September 27, 2024 23:34
Show Gist options
  • Select an option

  • Save dylanwh/89aff363f1e38ca7e081ac17a038da77 to your computer and use it in GitHub Desktop.

Select an option

Save dylanwh/89aff363f1e38ca7e081ac17a038da77 to your computer and use it in GitHub Desktop.
use std::{os::unix::prelude::ExitStatusExt, process::ExitCode};
fn main() -> std::io::Result<ExitCode> {
let (cmd, args) = match std::env::args().nth(1) {
Some(cmd) => (cmd, std::env::args().skip(2).collect::<Vec<String>>()),
None => {
eprintln!(
"Usage: {} <command> [args...]",
std::env::args().next().unwrap()
);
return Ok(ExitCode::FAILURE);
}
};
let max_sleep = 30;
let mut sleep = 1;
loop {
let mut command = std::process::Command::new(&cmd).args(&args).spawn()?;
let status = command.wait()?;
let signal = status.signal();
let code = status.code();
match (signal, code) {
(_, Some(0)) => break,
(Some(9), _) => {
eprintln!("{}: terminated by signal 9. Exiting", cmd);
break;
}
(Some(signal), _) => {
eprintln!("{}: terminated by signal {}. Retrying in {} seconds", cmd, signal, sleep);
}
(_, Some(code)) => {
eprintln!("{}: exited with status {}. Retrying in {} seconds", cmd, code, sleep);
}
(None, None) => {
eprintln!("{}: terminated by unknown means. Retrying in {} seconds", cmd, sleep);
break;
}
}
std::thread::sleep(std::time::Duration::from_secs(sleep));
sleep = std::cmp::min(sleep * 2, max_sleep);
}
Ok(ExitCode::SUCCESS)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment