1#[cfg(target_os = "macos")]
2use chrono::{Local, TimeZone};
3#[cfg(windows)]
4use itertools::Itertools;
5use nu_engine::command_prelude::*;
6
7use nu_protocol::PipelineMetadata;
8#[cfg(target_os = "linux")]
9use procfs::WithCurrentSystemInfo;
10use std::time::Duration;
11
12#[derive(Clone)]
13pub struct Ps;
14
15impl Command for Ps {
16 fn name(&self) -> &str {
17 "ps"
18 }
19
20 fn signature(&self) -> Signature {
21 Signature::build("ps")
22 .input_output_types(vec![(Type::Nothing, Type::table())])
23 .switch(
24 "long",
25 "List all available columns for each entry.",
26 Some('l'),
27 )
28 .filter()
29 .category(Category::System)
30 }
31
32 fn description(&self) -> &str {
33 "View information about system processes."
34 }
35
36 fn search_terms(&self) -> Vec<&str> {
37 vec![
38 "procedures",
39 "operations",
40 "tasks",
41 "ops",
42 "top",
43 "tasklist",
44 ]
45 }
46
47 fn run(
48 &self,
49 engine_state: &EngineState,
50 stack: &mut Stack,
51 call: &Call,
52 _input: PipelineData,
53 ) -> Result<PipelineData, ShellError> {
54 run_ps(engine_state, stack, call)
55 }
56
57 fn examples(&self) -> Vec<Example<'_>> {
58 vec![
59 Example {
60 description: "List the system processes",
61 example: "ps",
62 result: None,
63 },
64 Example {
65 description: "List the top 5 system processes with the highest memory usage",
66 example: "ps | sort-by mem | last 5",
67 result: None,
68 },
69 Example {
70 description: "List the top 3 system processes with the highest CPU usage",
71 example: "ps | sort-by cpu | last 3",
72 result: None,
73 },
74 Example {
75 description: "List the system processes with 'nu' in their names",
76 example: "ps | where name =~ 'nu'",
77 result: None,
78 },
79 Example {
80 description: "Get the parent process id of the current nu process",
81 example: "ps | where pid == $nu.pid | get ppid",
82 result: None,
83 },
84 ]
85 }
86}
87
88fn run_ps(
89 engine_state: &EngineState,
90 stack: &mut Stack,
91 call: &Call,
92) -> Result<PipelineData, ShellError> {
93 let mut output = vec![];
94 let span = call.head;
95 let long = call.has_flag(engine_state, stack, "long")?;
96
97 for proc in nu_system::collect_proc(Duration::from_millis(100), false) {
98 let mut record = Record::new();
99
100 record.push("pid", Value::int(proc.pid() as i64, span));
101 record.push("ppid", Value::int(proc.ppid() as i64, span));
102 record.push("name", Value::string(proc.name(), span));
103
104 #[cfg(not(windows))]
105 {
106 record.push("status", Value::string(proc.status(), span));
108 }
109
110 record.push("cpu", Value::float(proc.cpu_usage(), span));
111 record.push("mem", Value::filesize(proc.mem_size() as i64, span));
112 record.push("virtual", Value::filesize(proc.virtual_size() as i64, span));
113
114 if long {
115 record.push("command", Value::string(proc.command(), span));
116 #[cfg(target_os = "linux")]
117 {
118 let Ok(proc_stat) = proc.curr_proc.stat() else {
119 continue;
120 };
121 record.push(
122 "start_time",
123 match proc_stat.starttime().get() {
124 Ok(ts) => Value::date(ts.into(), span),
125 Err(_) => Value::nothing(span),
126 },
127 );
128 record.push("user_id", Value::int(proc.curr_proc.owner() as i64, span));
129 record.push("process_group_id", Value::int(proc_stat.pgrp as i64, span));
130 record.push("session_id", Value::int(proc_stat.session as i64, span));
131 record.push("priority", Value::int(proc_stat.priority, span));
134 record.push("process_threads", Value::int(proc_stat.num_threads, span));
135 record.push("working", Value::filesize(proc.working_size() as i64, span));
136 record.push("paged", Value::filesize(proc.paged_size() as i64, span));
137 record.push("cwd", Value::string(proc.cwd(), span));
138 }
139 #[cfg(windows)]
140 {
141 record.push(
144 "start_time",
145 Value::date(proc.start_time.fixed_offset(), span),
146 );
147 record.push(
148 "user",
149 Value::string(
150 proc.user.clone().name.unwrap_or("unknown".to_string()),
151 span,
152 ),
153 );
154 record.push(
155 "user_sid",
156 Value::string(
157 proc.user
158 .clone()
159 .sid
160 .iter()
161 .map(|r| r.to_string())
162 .join("-"),
163 span,
164 ),
165 );
166 record.push("priority", Value::int(proc.priority as i64, span));
167 record.push("working", Value::filesize(proc.working_size() as i64, span));
168 record.push("paged", Value::filesize(proc.paged_size() as i64, span));
169 record.push("cwd", Value::string(proc.cwd(), span));
170 record.push(
171 "environment",
172 Value::list(
173 proc.environ()
174 .iter()
175 .map(|x| Value::string(x.to_string(), span))
176 .collect(),
177 span,
178 ),
179 );
180 }
181 #[cfg(target_os = "macos")]
182 {
183 let timestamp = Local
184 .timestamp_nanos(proc.start_time * 1_000_000_000)
185 .into();
186 record.push("start_time", Value::date(timestamp, span));
187 record.push("user_id", Value::int(proc.user_id, span));
188 record.push("priority", Value::int(proc.priority, span));
189 record.push("process_threads", Value::int(proc.task_thread_num, span));
190 record.push("cwd", Value::string(proc.cwd(), span));
191 }
192 }
193
194 output.push(Value::record(record, span));
195 }
196
197 Ok(output.into_pipeline_data_with_metadata(
198 span,
199 engine_state.signals().clone(),
200 ps_pipeline_metadata(long, span),
201 ))
202}
203
204fn ps_pipeline_metadata(long: bool, span: Span) -> PipelineMetadata {
206 let width_priority_columns: &[&str] = if long {
207 &["command", "name"]
208 } else {
209 &["name"]
210 };
211
212 PipelineMetadata::default().with_table_width_priority_columns(span, width_priority_columns)
213}