nu_command/platform/
kill.rs

1use nu_engine::command_prelude::*;
2use nu_system::build_kill_command;
3use std::process::Stdio;
4
5#[derive(Clone)]
6pub struct Kill;
7
8impl Command for Kill {
9    fn name(&self) -> &str {
10        "kill"
11    }
12
13    fn description(&self) -> &str {
14        "Kill a process using the process id."
15    }
16
17    fn signature(&self) -> Signature {
18        let signature = Signature::build("kill")
19            .input_output_types(vec![(Type::Nothing, Type::Any)])
20            .allow_variants_without_examples(true)
21            .rest(
22                "pid",
23                SyntaxShape::Int,
24                "Process ids of processes that are to be killed.",
25            )
26            .switch("force", "forcefully kill the process", Some('f'))
27            .switch("quiet", "won't print anything to the console", Some('q'))
28            .category(Category::Platform);
29
30        if cfg!(windows) {
31            return signature;
32        }
33
34        signature.named(
35            "signal",
36            SyntaxShape::Int,
37            "signal decimal number to be sent instead of the default 15 (unsupported on Windows)",
38            Some('s'),
39        )
40    }
41
42    fn search_terms(&self) -> Vec<&str> {
43        vec!["stop", "end", "close"]
44    }
45
46    fn run(
47        &self,
48        engine_state: &EngineState,
49        stack: &mut Stack,
50        call: &Call,
51        _input: PipelineData,
52    ) -> Result<PipelineData, ShellError> {
53        let pids: Vec<i64> = call.rest(engine_state, stack, 0)?;
54        let force: bool = call.has_flag(engine_state, stack, "force")?;
55        let signal: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "signal")?;
56        let quiet: bool = call.has_flag(engine_state, stack, "quiet")?;
57
58        if pids.is_empty() {
59            return Err(ShellError::MissingParameter {
60                param_name: "pid".to_string(),
61                span: call.arguments_span(),
62            });
63        }
64
65        if cfg!(unix)
66            && let (
67                true,
68                Some(Spanned {
69                    item: _,
70                    span: signal_span,
71                }),
72            ) = (force, signal)
73        {
74            return Err(ShellError::IncompatibleParameters {
75                left_message: "force".to_string(),
76                left_span: call
77                    .get_flag_span(stack, "force")
78                    .expect("Had flag force, but didn't have span for flag"),
79                right_message: "signal".to_string(),
80                right_span: Span::merge(
81                    call.get_flag_span(stack, "signal")
82                        .expect("Had flag signal, but didn't have span for flag"),
83                    signal_span,
84                ),
85            });
86        };
87
88        let mut cmd = build_kill_command(
89            force,
90            pids.iter().copied(),
91            signal.map(|spanned| spanned.item as u32),
92        );
93
94        // pipe everything to null
95        if quiet {
96            cmd.stdin(Stdio::null())
97                .stdout(Stdio::null())
98                .stderr(Stdio::null());
99        }
100
101        let output = cmd.output().map_err(|e| ShellError::GenericError {
102            error: "failed to execute shell command".into(),
103            msg: e.to_string(),
104            span: Some(call.head),
105            help: None,
106            inner: vec![],
107        })?;
108
109        if !quiet && !output.status.success() {
110            return Err(ShellError::GenericError {
111                error: "process didn't terminate successfully".into(),
112                msg: String::from_utf8(output.stderr).unwrap_or_default(),
113                span: Some(call.head),
114                help: None,
115                inner: vec![],
116            });
117        }
118
119        let mut output =
120            String::from_utf8(output.stdout).map_err(|e| ShellError::GenericError {
121                error: "failed to convert output to string".into(),
122                msg: e.to_string(),
123                span: Some(call.head),
124                help: None,
125                inner: vec![],
126            })?;
127
128        output.truncate(output.trim_end().len());
129
130        if output.is_empty() {
131            Ok(Value::nothing(call.head).into_pipeline_data())
132        } else {
133            Ok(Value::string(output, call.head).into_pipeline_data())
134        }
135    }
136
137    fn examples(&self) -> Vec<Example<'_>> {
138        vec![
139            Example {
140                description: "Kill the pid using the most memory",
141                example: "ps | sort-by mem | last | kill $in.pid",
142                result: None,
143            },
144            Example {
145                description: "Force kill a given pid",
146                example: "kill --force 12345",
147                result: None,
148            },
149            #[cfg(not(target_os = "windows"))]
150            Example {
151                description: "Send INT signal",
152                example: "kill -s 2 12345",
153                result: None,
154            },
155        ]
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::Kill;
162
163    #[test]
164    fn examples_work_as_expected() {
165        use crate::test_examples;
166        test_examples(Kill {})
167    }
168}