Skip to content

Commit

Permalink
app: Spawn using double-fork
Browse files Browse the repository at this point in the history
  • Loading branch information
Drakulix committed Nov 6, 2023
1 parent aecff8e commit 2a35331
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 2 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ itertools = "0.11"
freedesktop-icons = "0.2.4"
current_locale = "0.1.1"
url = "2.4"
nix = "0.26"

[profile.release]
lto = "thin"
6 changes: 4 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ impl cosmic::Application for CosmicAppLibrary {
Message::ActivationToken(token, exec) => {
let mut exec = shlex::Shlex::new(&exec);
let mut cmd = match exec.next() {
Some(cmd) if !cmd.contains("=") => tokio::process::Command::new(cmd),
Some(cmd) if !cmd.contains("=") => std::process::Command::new(cmd),
_ => return Command::none(),
};
for arg in exec {
Expand All @@ -252,7 +252,9 @@ impl cosmic::Application for CosmicAppLibrary {
cmd.env("XDG_ACTIVATION_TOKEN", token.clone());
cmd.env("DESKTOP_STARTUP_ID", token);
}
let _ = cmd.spawn();
tokio::task::spawn_blocking(|| {
crate::process::spawn(cmd);
});
return self.update(Message::Hide);
}
Message::SelectGroup(i) => {
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod config;
mod app;
mod app_group;
mod localize;
pub mod process;
mod subscriptions;
mod widgets;

Expand Down
31 changes: 31 additions & 0 deletions src/process.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::process::{exit, Command, Stdio};

use nix::sys::wait::waitpid;
use nix::unistd::{fork, ForkResult};

/// Performs a double fork with setsid to spawn and detach a command.
pub fn spawn(mut command: Command) {
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());

unsafe {
match fork() {
Ok(ForkResult::Parent { child }) => {
let _res = waitpid(Some(child), None);
}

Ok(ForkResult::Child) => {
let _res = nix::unistd::setsid();
let _res = command.spawn();

exit(0);
}

Err(why) => {
println!("failed to fork and spawn command: {}", why.desc());
}
}
}
}

0 comments on commit 2a35331

Please sign in to comment.