Skip to content

Instantly share code, notes, and snippets.

@numberoverzero
Created November 6, 2021 07:44
Show Gist options
  • Save numberoverzero/50d8c60e9dd47e7f6608f57abf6f98b6 to your computer and use it in GitHub Desktop.
Save numberoverzero/50d8c60e9dd47e7f6608f57abf6f98b6 to your computer and use it in GitHub Desktop.
execute a function in a detached process and exit
// fork = "0.1"
use fork::{self, Fork};
use std::process;
/// no error handling, no logging, just one shot to run in a forked process
fn run_forked<R>(f: fn() -> R) -> bool
{
match fork::fork() {
Ok(Fork::Parent(_)) => {
// we're in the parent process, must have forked successfully
return true;
},
Ok(Fork::Child) => {
// we're in the child process
fork::setsid().unwrap(); // YOLO: just panic
f();
process::exit(0);
},
Err(_) => {
// failed to fork
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment