cosmic_files/
spawn_detached.rs

1use std::{io, process};
2
3// This code is from the open crate and retains its MIT license.
4pub fn spawn_detached(command: &mut process::Command) -> io::Result<()> {
5    command
6        .stdin(process::Stdio::null())
7        .stdout(process::Stdio::null())
8        .stderr(process::Stdio::null());
9
10    #[cfg(unix)]
11    unsafe {
12        use std::os::unix::process::CommandExt as _;
13
14        command
15            .pre_exec(move || {
16                match libc::fork() {
17                    -1 => return Err(io::Error::last_os_error()),
18                    0 => (),
19                    _ => libc::_exit(0),
20                }
21
22                if libc::setsid() == -1 {
23                    return Err(io::Error::last_os_error());
24                }
25
26                Ok(())
27            })
28            .spawn()?
29            .wait()
30            .map(|_| ())
31    }
32    #[cfg(windows)]
33    {
34        use std::os::windows::process::CommandExt;
35        const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
36        const CREATE_NO_WINDOW: u32 = 0x08000000;
37        command
38            .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
39            .spawn()
40            .map(|_| ())
41    }
42}