use std::io;
use std::path::{Path, absolute};
use std::process::{Command, Stdio};
pub const LANDER_URL: &str = "NEOSIAN_LANDER_URL";
pub struct Lander<'a> {
pub home: &'a Path,
pub spool: Option<&'a Path>,
pub url: Option<&'a str>,
}
pub fn command(lander: &Lander) -> io::Result<Command> {
let home = absolute(lander.home)?;
let mut command = Command::new(std::env::current_exe()?);
command.arg("record-land").arg("--home").arg(&home);
if let Some(spool) = lander.spool {
command.arg("--spool").arg(absolute(spool)?);
}
match lander.url {
Some(url) => command.env(LANDER_URL, url),
None => command.env_remove(LANDER_URL),
};
command
.current_dir(&home)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
Ok(command)
}
pub fn spawn(lander: &Lander) -> io::Result<()> {
let mut command = command(lander)?;
detach(&mut command);
command.spawn().map(drop)
}
#[cfg(unix)]
fn detach(command: &mut Command) {
use std::os::unix::process::CommandExt;
unsafe extern "C" {
fn setsid() -> i32;
}
unsafe {
command.pre_exec(|| {
if setsid() == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
});
}
}
#[cfg(windows)]
fn detach(command: &mut Command) {
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use windows_sys::Win32::Foundation::{HANDLE_FLAG_INHERIT, SetHandleInformation};
use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, DETACHED_PROCESS};
let handles = [
io::stdin().as_raw_handle(),
io::stdout().as_raw_handle(),
io::stderr().as_raw_handle(),
];
for handle in handles {
if !handle.is_null() {
unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) };
}
}
command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
}