Renan Ribeiro 9bb7f0c7dc
Jobs (#14883)
# Description

This is an attempt to improve the nushell situation with regard to issue
#247.

This PR implements:
- [X] spawning jobs: `job spawn { do_background_thing }`
Jobs will be implemented as threads and not forks, to maintain a
consistent behavior between unix and windows.

- [X] listing running jobs: `job list`
This should allow users to list what background tasks they currently
have running.

- [X] killing jobs: `job kill <id>`
- [X] interupting nushell code in the job's background thread
- [X] interrupting the job's currently-running process, if any.

Things that should be taken into consideration for implementation:
- [X] (unix-only) Handling `TSTP` signals while executing code and
turning the current program into a background job, and unfreezing them
in foreground `job unfreeze`.

- [X] Ensuring processes spawned by background jobs get distinct process
groups from the nushell shell itself

This PR originally aimed to implement some of the following, but it is
probably ideal to be left for another PR (scope creep)
- Disowning external process jobs (`job dispatch`)
- Inter job communication (`job send/recv`)

Roadblocks encountered so far:
- Nushell does some weird terminal sequence magics which make so that
when a background process or thread prints something to stderr and the
prompt is idle, the stderr output ends up showing up weirdly
2025-02-25 12:09:52 -05:00

55 lines
1.3 KiB
Rust

use std::io;
use std::process::Command as CommandSys;
/// Tries to forcefully kill a process by its PID
pub fn kill_by_pid(pid: i64) -> io::Result<()> {
let mut cmd = build_kill_command(true, std::iter::once(pid), None);
let output = cmd.output()?;
if !output.status.success() {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to kill process",
));
}
Ok(())
}
/// Create a `std::process::Command` for the current target platform, for killing
/// the processes with the given PIDs
pub fn build_kill_command(
force: bool,
pids: impl Iterator<Item = i64>,
signal: Option<u32>,
) -> CommandSys {
if cfg!(windows) {
let mut cmd = CommandSys::new("taskkill");
if force {
cmd.arg("/F");
}
// each pid must written as `/PID 0` otherwise
// taskkill will act as `killall` unix command
for id in pids {
cmd.arg("/PID");
cmd.arg(id.to_string());
}
cmd
} else {
let mut cmd = CommandSys::new("kill");
if let Some(signal_value) = signal {
cmd.arg(format!("-{}", signal_value));
} else if force {
cmd.arg("-9");
}
cmd.args(pids.map(move |id| id.to_string()));
cmd
}
}