pub struct Process { /* private fields */ }Expand description
Struct containing information of a process.
§iOS
This information cannot be retrieved on iOS due to sandboxing.
§Apple app store
If you are building a macOS Apple app store, it won’t be able to retrieve this information.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.name());
}Implementations§
Source§impl Process
impl Process
Sourcepub fn kill(&self) -> bool
pub fn kill(&self) -> bool
Sends Signal::Kill to the process (which is the only signal supported on all supported
platforms by this crate).
Returns true if the signal was sent successfully. If you want to wait for this process
to end, you can use Process::wait or directly Process::kill_and_wait.
⚠️ Even if this function returns true, it doesn’t necessarily mean that the process will
be killed. It just means that the signal was sent successfully.
⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example.
If you want to use another signal, take a look at Process::kill_with.
To get the list of the supported signals on this system, use
SUPPORTED_SIGNALS.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
process.kill();
}Sourcepub fn kill_with(&self, signal: Signal) -> Option<bool>
pub fn kill_with(&self, signal: Signal) -> Option<bool>
Sends the given signal to the process. If the signal doesn’t exist on this platform,
it’ll do nothing and will return None. Otherwise it’ll return Some(bool). The boolean
value will depend on whether or not the signal was sent successfully.
If you just want to kill the process, use Process::kill directly. If you want to wait
for this process to end, you can use Process::wait or Process::kill_with_and_wait.
⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example.
To get the list of the supported signals on this system, use
SUPPORTED_SIGNALS.
use sysinfo::{Pid, Signal, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
if process.kill_with(Signal::Kill).is_none() {
println!("This signal isn't supported on this platform");
}
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage(),);
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups(),);
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn kill_and_wait(&self) -> Result<Option<ExitStatus>, KillError>
pub fn kill_and_wait(&self) -> Result<Option<ExitStatus>, KillError>
Sends Signal::Kill to the process then waits for its termination.
Internally, this method is calling Process::kill then Process::wait.
⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example. In this case, this method could enter an infinite loop.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
if let Err(error) = process.kill_and_wait() {
println!("`kill_and_wait` failed: {error:?}");
}
}Sourcepub fn kill_with_and_wait(
&self,
signal: Signal,
) -> Result<Option<ExitStatus>, KillError>
pub fn kill_with_and_wait( &self, signal: Signal, ) -> Result<Option<ExitStatus>, KillError>
Sends the given signal to the process.then waits for its termination.
Internally, this method is calling Process::kill_with then Process::wait.
⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example. In this case, this method could enter an infinite loop.
To get the list of the supported signals on this system, use
SUPPORTED_SIGNALS.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
if let Err(error) = process.kill_and_wait() {
println!("`kill_and_wait` failed: {error:?}");
}
}Sourcepub fn wait(&self) -> Option<ExitStatus>
pub fn wait(&self) -> Option<ExitStatus>
Waits for process termination and returns its [ExitStatus] if it could be retrieved,
returns None otherwise. It means that as long as the process is alive, this method will
not return.
⚠️ On macOS and FreeBSD, if the process died and a new one took its PID, unless you refreshed, it will wait for the new process to end.
On Windows, as long as we have a (internal) handle, we can always retrieve the exit status.
On Linux/Android, we check that the start time of the PID we’re waiting is the same as the current process’. If not it means the process died and a new one got its PID.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("Waiting for pid 1337");
let exit_status = process.wait();
println!("Pid 1337 exited with: {exit_status:?}");
}Sourcepub fn name(&self) -> &OsStr
pub fn name(&self) -> &OsStr
Returns the name of the process.
⚠️ Important ⚠️
On Linux, there are two things to know about processes’ name:
- It is limited to 15 characters.
- It is not always the exe name.
If you are looking for a specific process, unless you know what you are
doing, in most cases it’s better to use Process::exe instead (which
can be empty sometimes!).
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.name());
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage(),);
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups(),);
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn cmd(&self) -> &[OsString]
pub fn cmd(&self) -> &[OsString]
Returns the command line.
⚠️ Important ⚠️
On Windows, you might need to use administrator privileges when running your program
to have access to this information.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.cmd());
}Sourcepub fn exe(&self) -> Option<&Path>
pub fn exe(&self) -> Option<&Path>
Returns the path to the process.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.exe());
}§Implementation notes
On Linux, this method will return an empty path if there
was an error trying to read /proc/<pid>/exe. This can
happen, for example, if the permission levels or UID namespaces
between the caller and target processes are different.
It is also the case that cmd[0] is not usually a correct
replacement for this.
A process may change its cmd[0] value
freely, making this an untrustworthy source of information.
Sourcepub fn pid(&self) -> Pid
pub fn pid(&self) -> Pid
Returns the PID of the process.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{}", process.pid());
}Sourcepub fn environ(&self) -> &[OsString]
pub fn environ(&self) -> &[OsString]
Returns the environment variables of the process.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.environ());
}Sourcepub fn cwd(&self) -> Option<&Path>
pub fn cwd(&self) -> Option<&Path>
Returns the current working directory.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.cwd());
}Sourcepub fn root(&self) -> Option<&Path>
pub fn root(&self) -> Option<&Path>
Returns the path of the root directory.
⚠️ Not implemented in NetBSD.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.root());
}Sourcepub fn memory(&self) -> u64
pub fn memory(&self) -> u64
Returns the memory usage (in bytes).
This method returns the size of the resident set, that is, the amount of memory that the process allocated and which is currently mapped in physical RAM. It does not include memory that is swapped out, or, in some operating systems, that has been allocated but never used.
Thus, it represents exactly the amount of physical RAM that the process is using at the
present time, but it might not be a good indicator of the total memory that the process will
be using over its lifetime. For that purpose, you can try and use
virtual_memory.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{} bytes", process.memory());
}Sourcepub fn virtual_memory(&self) -> u64
pub fn virtual_memory(&self) -> u64
Returns the virtual memory usage (in bytes).
This method returns the size of virtual memory, that is, the amount of memory that the process can access, whether it is currently mapped in physical RAM or not. It includes physical RAM, allocated but not used regions, swapped-out regions, and even memory associated with memory-mapped files.
This value has limitations though. Depending on the operating system and type of process, this value might be a good indicator of the total memory that the process will be using over its lifetime. However, for example, in the version 14 of macOS this value is in the order of the hundreds of gigabytes for every process, and thus not very informative. Moreover, if a process maps into memory a very large file, this value will increase accordingly, even if the process is not actively using the memory.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{} bytes", process.virtual_memory());
}Sourcepub fn parent(&self) -> Option<Pid>
pub fn parent(&self) -> Option<Pid>
Returns the parent PID.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.parent());
}Sourcepub fn status(&self) -> ProcessStatus
pub fn status(&self) -> ProcessStatus
Returns the status of the process.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.status());
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage(),);
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups(),);
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn start_time(&self) -> u64
pub fn start_time(&self) -> u64
Returns the time where the process was started (in seconds) from epoch.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("Started at {} seconds", process.start_time());
}Sourcepub fn run_time(&self) -> u64
pub fn run_time(&self) -> u64
Returns for how much time the process has been running (in seconds).
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("Running since {} seconds", process.run_time());
}Sourcepub fn cpu_usage(&self) -> f32
pub fn cpu_usage(&self) -> f32
Returns the total CPU usage (in %). Notice that it might be bigger than 100 if run on a multi-core machine.
If you want a value between 0% and 100%, divide the returned value by the number of CPUs.
⚠️ To start to have accurate CPU usage, a process needs to be refreshed twice because CPU usage computation is based on time diff (process time on a given time period divided by total system time on the same time period).
⚠️ If you want accurate CPU usage number, better leave a bit of time
between two calls of this method (take a look at
MINIMUM_CPU_UPDATE_INTERVAL for
more information).
use sysinfo::{Pid, ProcessesToUpdate, ProcessRefreshKind, System};
let mut s = System::new_all();
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPU usage to get actual value.
s.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing().with_cpu()
);
if let Some(process) = s.process(Pid::from(1337)) {
println!("{}%", process.cpu_usage());
}Sourcepub fn accumulated_cpu_time(&self) -> u64
pub fn accumulated_cpu_time(&self) -> u64
Returns the total accumulated CPU usage (in CPU-milliseconds). Note that it might be bigger than the total clock run time of a process if run on a multi-core machine.
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{}", process.accumulated_cpu_time());
}Sourcepub fn disk_usage(&self) -> DiskUsage
pub fn disk_usage(&self) -> DiskUsage
Returns number of bytes read and written to disk.
⚠️ On Windows, this method actually returns ALL I/O read and written bytes.
⚠️ Files might be cached in memory by your OS, meaning that reading/writing them might not
increase the read_bytes/written_bytes values. You can find more information about it
in the proc_pid_io manual (man proc_pid_io on unix platforms).
use sysinfo::{Pid, System};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
let disk_usage = process.disk_usage();
println!("read bytes : new/total => {}/{}",
disk_usage.read_bytes,
disk_usage.total_read_bytes,
);
println!("written bytes: new/total => {}/{}",
disk_usage.written_bytes,
disk_usage.total_written_bytes,
);
}Sourcepub fn user_id(&self) -> Option<&Uid>
pub fn user_id(&self) -> Option<&Uid>
Returns the ID of the owner user of this process or None if this
information couldn’t be retrieved. If you want to get the User from
it, take a look at Users::get_user_by_id.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("User id for process 1337: {:?}", process.user_id());
}Sourcepub fn effective_user_id(&self) -> Option<&Uid>
pub fn effective_user_id(&self) -> Option<&Uid>
Returns the user ID of the effective owner of this process or None if
this information couldn’t be retrieved. If you want to get the User
from it, take a look at Users::get_user_by_id.
If you run something with sudo, the real user ID of the launched
process will be the ID of the user you are logged in as but effective
user ID will be 0 (i-e root).
⚠️ It always returns None on Windows.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("User id for process 1337: {:?}", process.effective_user_id());
}Sourcepub fn group_id(&self) -> Option<Gid>
pub fn group_id(&self) -> Option<Gid>
Returns the process group ID of the process.
⚠️ It always returns None on Windows.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("Group ID for process 1337: {:?}", process.group_id());
}Sourcepub fn effective_group_id(&self) -> Option<Gid>
pub fn effective_group_id(&self) -> Option<Gid>
Returns the effective group ID of the process.
If you run something with sudo, the real group ID of the launched
process will be the primary group ID you are logged in as but effective
group ID will be 0 (i-e root).
⚠️ It always returns None on Windows.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("User id for process 1337: {:?}", process.effective_group_id());
}Sourcepub fn session_id(&self) -> Option<Pid>
pub fn session_id(&self) -> Option<Pid>
Returns the session ID for the current process or None if it couldn’t
be retrieved.
⚠️ This information is computed every time this method is called.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("Session ID for process 1337: {:?}", process.session_id());
}Sourcepub fn tasks(&self) -> Option<&HashSet<Pid>>
pub fn tasks(&self) -> Option<&HashSet<Pid>>
Tasks run by this process. If there are none, returns None.
⚠️ This method always returns None on other platforms than Linux.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
if let Some(tasks) = process.tasks() {
println!("Listing tasks for process {:?}", process.pid());
for task_pid in tasks {
if let Some(task) = s.process(*task_pid) {
println!("Task {:?}: {:?}", task.pid(), task.name());
}
}
}
}Sourcepub fn thread_kind(&self) -> Option<ThreadKind>
pub fn thread_kind(&self) -> Option<ThreadKind>
If the process is a thread, it’ll return Some with the kind of thread it is. Returns
None otherwise.
⚠️ This method always returns None on other platforms than Linux.
use sysinfo::System;
let s = System::new_all();
for (_, process) in s.processes() {
if let Some(thread_kind) = process.thread_kind() {
println!("Process {:?} is a {thread_kind:?} thread", process.pid());
}
}Sourcepub fn exists(&self) -> bool
pub fn exists(&self) -> bool
Returns true if the process doesn’t exist anymore but was not yet removed from
the processes list because the remove_dead_processes argument was set to false
in methods like System::refresh_processes.
use sysinfo::{ProcessesToUpdate, System};
let mut s = System::new_all();
// We set the `remove_dead_processes` to `false`.
s.refresh_processes(ProcessesToUpdate::All, false);
for (_, process) in s.processes() {
println!(
"Process {:?} {}",
process.pid(),
if process.exists() { "exists" } else { "doesn't exist" },
);
}Sourcepub fn open_files(&self) -> Option<usize>
pub fn open_files(&self) -> Option<usize>
Returns the number of open files in the current process.
Returns None if it failed retrieving the information or if the current system is not
supported.
Important: this information is computed every time this function is called.
⚠️ Not implemented on NetBSD.
use sysinfo::System;
let s = System::new_all();
for (_, process) in s.processes() {
println!(
"Process {:?} {:?}",
process.pid(),
process.open_files(),
);
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage(),);
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups(),);
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn open_files_limit(&self) -> Option<usize>
pub fn open_files_limit(&self) -> Option<usize>
Returns the maximum number of open files for the current process.
Returns None if it failed retrieving the information or if the current system is not
supported.
Important: this information is computed every time this function is called.
use sysinfo::System;
let s = System::new_all();
for (_, process) in s.processes() {
println!(
"Process {:?} {:?}",
process.pid(),
process.open_files_limit(),
);
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage(),);
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups(),);
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}