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.
⚠️ 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.
⚠️ 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?
149fn interpret_input(
150 input: &str,
151 sys: &mut System,
152 networks: &mut Networks,
153 disks: &mut Disks,
154 components: &mut Components,
155 users: &mut Users,
156) -> bool {
157 match input.trim() {
158 "help" => print_help(),
159 "refresh_disks" => {
160 writeln!(&mut io::stdout(), "Refreshing disk list...");
161 disks.refresh(true);
162 writeln!(&mut io::stdout(), "Done.");
163 }
164 "refresh_users" => {
165 writeln!(&mut io::stdout(), "Refreshing user list...");
166 users.refresh();
167 writeln!(&mut io::stdout(), "Done.");
168 }
169 "refresh_networks" => {
170 writeln!(&mut io::stdout(), "Refreshing network list...");
171 networks.refresh(true);
172 writeln!(&mut io::stdout(), "Done.");
173 }
174 "refresh_components" => {
175 writeln!(&mut io::stdout(), "Refreshing component list...");
176 components.refresh(true);
177 writeln!(&mut io::stdout(), "Done.");
178 }
179 "refresh_cpu" => {
180 writeln!(&mut io::stdout(), "Refreshing CPUs...");
181 sys.refresh_cpu_all();
182 writeln!(&mut io::stdout(), "Done.");
183 }
184 "signals" => {
185 let mut nb = 1i32;
186
187 for sig in signals {
188 writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189 nb += 1;
190 }
191 }
192 "cpus" => {
193 // Note: you should refresh a few times before using this, so that usage statistics
194 // can be ascertained
195 writeln!(
196 &mut io::stdout(),
197 "number of physical cores: {}",
198 sys.physical_core_count()
199 .map(|c| c.to_string())
200 .unwrap_or_else(|| "Unknown".to_owned()),
201 );
202 writeln!(
203 &mut io::stdout(),
204 "total CPU usage: {}%",
205 sys.global_cpu_usage(),
206 );
207 for cpu in sys.cpus() {
208 writeln!(&mut io::stdout(), "{cpu:?}");
209 }
210 }
211 "memory" => {
212 writeln!(
213 &mut io::stdout(),
214 "total memory: {: >10} KB",
215 sys.total_memory() / 1_000
216 );
217 writeln!(
218 &mut io::stdout(),
219 "available memory: {: >10} KB",
220 sys.available_memory() / 1_000
221 );
222 writeln!(
223 &mut io::stdout(),
224 "used memory: {: >10} KB",
225 sys.used_memory() / 1_000
226 );
227 writeln!(
228 &mut io::stdout(),
229 "total swap: {: >10} KB",
230 sys.total_swap() / 1_000
231 );
232 writeln!(
233 &mut io::stdout(),
234 "used swap: {: >10} KB",
235 sys.used_swap() / 1_000
236 );
237 }
238 "quit" | "exit" => return true,
239 "all" => {
240 for (pid, proc_) in sys.processes() {
241 writeln!(
242 &mut io::stdout(),
243 "{}:{} status={:?}",
244 pid,
245 proc_.name().to_string_lossy(),
246 proc_.status()
247 );
248 }
249 }
250 "frequency" => {
251 for cpu in sys.cpus() {
252 writeln!(
253 &mut io::stdout(),
254 "[{}] {} MHz",
255 cpu.name(),
256 cpu.frequency(),
257 );
258 }
259 }
260 "vendor_id" => {
261 writeln!(
262 &mut io::stdout(),
263 "vendor ID: {}",
264 sys.cpus()[0].vendor_id()
265 );
266 }
267 "brand" => {
268 writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269 }
270 "load_avg" => {
271 let load_avg = System::load_average();
272 writeln!(&mut io::stdout(), "one minute : {}%", load_avg.one);
273 writeln!(&mut io::stdout(), "five minutes : {}%", load_avg.five);
274 writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275 }
276 e if e.starts_with("show ") => {
277 let tmp: Vec<&str> = e.split(' ').collect();
278
279 if tmp.len() != 2 {
280 writeln!(
281 &mut io::stdout(),
282 "show command takes a pid or a name in parameter!"
283 );
284 writeln!(&mut io::stdout(), "example: show 1254");
285 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286 match sys.process(pid) {
287 Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288 None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289 };
290 } else {
291 let proc_name = tmp[1];
292 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293 writeln!(
294 &mut io::stdout(),
295 "==== {} ====",
296 proc_.name().to_string_lossy()
297 );
298 writeln!(&mut io::stdout(), "{proc_:?}");
299 }
300 }
301 }
302 "temperature" => {
303 for component in components.iter() {
304 writeln!(&mut io::stdout(), "{component:?}");
305 }
306 }
307 "network" => {
308 for (interface_name, data) in networks.iter() {
309 writeln!(
310 &mut io::stdout(),
311 "{}:\n ether {}\n input data (new / total): {} / {} B\n output data (new / total): {} / {} B",
312 interface_name,
313 data.mac_address(),
314 data.received(),
315 data.total_received(),
316 data.transmitted(),
317 data.total_transmitted(),
318 );
319 }
320 }
321 "show" => {
322 writeln!(
323 &mut io::stdout(),
324 "'show' command expects a pid number or a process name"
325 );
326 }
327 e if e.starts_with("kill ") => {
328 let tmp: Vec<&str> = e.split(' ').collect();
329
330 if tmp.len() != 3 {
331 writeln!(
332 &mut io::stdout(),
333 "kill command takes the pid and a signal number in parameter!"
334 );
335 writeln!(&mut io::stdout(), "example: kill 1254 9");
336 } else {
337 let pid = Pid::from_str(tmp[1]).unwrap();
338 let signal = i32::from_str(tmp[2]).unwrap();
339
340 if signal < 1 || signal > 31 {
341 writeln!(
342 &mut io::stdout(),
343 "Signal must be between 0 and 32 ! See the signals list with the \
344 signals command"
345 );
346 } else {
347 match sys.process(pid) {
348 Some(p) => {
349 if let Some(res) =
350 p.kill_with(*signals.get(signal as usize - 1).unwrap())
351 {
352 writeln!(&mut io::stdout(), "kill: {res}");
353 } else {
354 writeln!(
355 &mut io::stdout(),
356 "kill: signal not supported on this platform"
357 );
358 }
359 }
360 None => {
361 writeln!(&mut io::stdout(), "pid not found");
362 }
363 };
364 }
365 }
366 }
367 "disks" => {
368 for disk in disks {
369 writeln!(&mut io::stdout(), "{disk:?}");
370 }
371 }
372 "users" => {
373 for user in users {
374 writeln!(
375 &mut io::stdout(),
376 "{:?} => {:?}",
377 user.name(),
378 user.groups()
379 );
380 }
381 }
382 "boot_time" => {
383 writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384 }
385 "uptime" => {
386 let up = System::uptime();
387 let mut uptime = up;
388 let days = uptime / 86400;
389 uptime -= days * 86400;
390 let hours = uptime / 3600;
391 uptime -= hours * 3600;
392 let minutes = uptime / 60;
393 writeln!(
394 &mut io::stdout(),
395 "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396 );
397 }
398 x if x.starts_with("refresh") => {
399 if x == "refresh" {
400 writeln!(&mut io::stdout(), "Getting processes' information...");
401 sys.refresh_all();
402 writeln!(&mut io::stdout(), "Done.");
403 } else if x.starts_with("refresh ") {
404 writeln!(&mut io::stdout(), "Getting process' information...");
405 if let Some(pid) = x
406 .split(' ')
407 .filter_map(|pid| pid.parse().ok())
408 .take(1)
409 .next()
410 {
411 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412 writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413 } else {
414 writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415 }
416 } else {
417 writeln!(&mut io::stdout(), "Invalid [pid] received...");
418 }
419 } else {
420 writeln!(
421 &mut io::stdout(),
422 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423 list.",
424 );
425 }
426 }
427 "pid" => {
428 writeln!(
429 &mut io::stdout(),
430 "PID: {}",
431 sysinfo::get_current_pid().expect("failed to get PID")
432 );
433 }
434 "system" => {
435 writeln!(
436 &mut io::stdout(),
437 "System name: {}\n\
438 System kernel version: {}\n\
439 System OS version: {}\n\
440 System OS (long) version: {}\n\
441 System host name: {}",
442 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447 );
448 }
449 e => {
450 writeln!(
451 &mut io::stdout(),
452 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453 list.",
454 );
455 }
456 }
457 false
458}Sourcepub fn wait(&self)
pub fn wait(&self)
Wait for process termination.
use sysinfo::{Pid, System};
let mut s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("Waiting for pid 1337");
process.wait();
println!("Pid 1337 exited");
}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?
149fn interpret_input(
150 input: &str,
151 sys: &mut System,
152 networks: &mut Networks,
153 disks: &mut Disks,
154 components: &mut Components,
155 users: &mut Users,
156) -> bool {
157 match input.trim() {
158 "help" => print_help(),
159 "refresh_disks" => {
160 writeln!(&mut io::stdout(), "Refreshing disk list...");
161 disks.refresh(true);
162 writeln!(&mut io::stdout(), "Done.");
163 }
164 "refresh_users" => {
165 writeln!(&mut io::stdout(), "Refreshing user list...");
166 users.refresh();
167 writeln!(&mut io::stdout(), "Done.");
168 }
169 "refresh_networks" => {
170 writeln!(&mut io::stdout(), "Refreshing network list...");
171 networks.refresh(true);
172 writeln!(&mut io::stdout(), "Done.");
173 }
174 "refresh_components" => {
175 writeln!(&mut io::stdout(), "Refreshing component list...");
176 components.refresh(true);
177 writeln!(&mut io::stdout(), "Done.");
178 }
179 "refresh_cpu" => {
180 writeln!(&mut io::stdout(), "Refreshing CPUs...");
181 sys.refresh_cpu_all();
182 writeln!(&mut io::stdout(), "Done.");
183 }
184 "signals" => {
185 let mut nb = 1i32;
186
187 for sig in signals {
188 writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189 nb += 1;
190 }
191 }
192 "cpus" => {
193 // Note: you should refresh a few times before using this, so that usage statistics
194 // can be ascertained
195 writeln!(
196 &mut io::stdout(),
197 "number of physical cores: {}",
198 sys.physical_core_count()
199 .map(|c| c.to_string())
200 .unwrap_or_else(|| "Unknown".to_owned()),
201 );
202 writeln!(
203 &mut io::stdout(),
204 "total CPU usage: {}%",
205 sys.global_cpu_usage(),
206 );
207 for cpu in sys.cpus() {
208 writeln!(&mut io::stdout(), "{cpu:?}");
209 }
210 }
211 "memory" => {
212 writeln!(
213 &mut io::stdout(),
214 "total memory: {: >10} KB",
215 sys.total_memory() / 1_000
216 );
217 writeln!(
218 &mut io::stdout(),
219 "available memory: {: >10} KB",
220 sys.available_memory() / 1_000
221 );
222 writeln!(
223 &mut io::stdout(),
224 "used memory: {: >10} KB",
225 sys.used_memory() / 1_000
226 );
227 writeln!(
228 &mut io::stdout(),
229 "total swap: {: >10} KB",
230 sys.total_swap() / 1_000
231 );
232 writeln!(
233 &mut io::stdout(),
234 "used swap: {: >10} KB",
235 sys.used_swap() / 1_000
236 );
237 }
238 "quit" | "exit" => return true,
239 "all" => {
240 for (pid, proc_) in sys.processes() {
241 writeln!(
242 &mut io::stdout(),
243 "{}:{} status={:?}",
244 pid,
245 proc_.name().to_string_lossy(),
246 proc_.status()
247 );
248 }
249 }
250 "frequency" => {
251 for cpu in sys.cpus() {
252 writeln!(
253 &mut io::stdout(),
254 "[{}] {} MHz",
255 cpu.name(),
256 cpu.frequency(),
257 );
258 }
259 }
260 "vendor_id" => {
261 writeln!(
262 &mut io::stdout(),
263 "vendor ID: {}",
264 sys.cpus()[0].vendor_id()
265 );
266 }
267 "brand" => {
268 writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269 }
270 "load_avg" => {
271 let load_avg = System::load_average();
272 writeln!(&mut io::stdout(), "one minute : {}%", load_avg.one);
273 writeln!(&mut io::stdout(), "five minutes : {}%", load_avg.five);
274 writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275 }
276 e if e.starts_with("show ") => {
277 let tmp: Vec<&str> = e.split(' ').collect();
278
279 if tmp.len() != 2 {
280 writeln!(
281 &mut io::stdout(),
282 "show command takes a pid or a name in parameter!"
283 );
284 writeln!(&mut io::stdout(), "example: show 1254");
285 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286 match sys.process(pid) {
287 Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288 None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289 };
290 } else {
291 let proc_name = tmp[1];
292 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293 writeln!(
294 &mut io::stdout(),
295 "==== {} ====",
296 proc_.name().to_string_lossy()
297 );
298 writeln!(&mut io::stdout(), "{proc_:?}");
299 }
300 }
301 }
302 "temperature" => {
303 for component in components.iter() {
304 writeln!(&mut io::stdout(), "{component:?}");
305 }
306 }
307 "network" => {
308 for (interface_name, data) in networks.iter() {
309 writeln!(
310 &mut io::stdout(),
311 "{}:\n ether {}\n input data (new / total): {} / {} B\n output data (new / total): {} / {} B",
312 interface_name,
313 data.mac_address(),
314 data.received(),
315 data.total_received(),
316 data.transmitted(),
317 data.total_transmitted(),
318 );
319 }
320 }
321 "show" => {
322 writeln!(
323 &mut io::stdout(),
324 "'show' command expects a pid number or a process name"
325 );
326 }
327 e if e.starts_with("kill ") => {
328 let tmp: Vec<&str> = e.split(' ').collect();
329
330 if tmp.len() != 3 {
331 writeln!(
332 &mut io::stdout(),
333 "kill command takes the pid and a signal number in parameter!"
334 );
335 writeln!(&mut io::stdout(), "example: kill 1254 9");
336 } else {
337 let pid = Pid::from_str(tmp[1]).unwrap();
338 let signal = i32::from_str(tmp[2]).unwrap();
339
340 if signal < 1 || signal > 31 {
341 writeln!(
342 &mut io::stdout(),
343 "Signal must be between 0 and 32 ! See the signals list with the \
344 signals command"
345 );
346 } else {
347 match sys.process(pid) {
348 Some(p) => {
349 if let Some(res) =
350 p.kill_with(*signals.get(signal as usize - 1).unwrap())
351 {
352 writeln!(&mut io::stdout(), "kill: {res}");
353 } else {
354 writeln!(
355 &mut io::stdout(),
356 "kill: signal not supported on this platform"
357 );
358 }
359 }
360 None => {
361 writeln!(&mut io::stdout(), "pid not found");
362 }
363 };
364 }
365 }
366 }
367 "disks" => {
368 for disk in disks {
369 writeln!(&mut io::stdout(), "{disk:?}");
370 }
371 }
372 "users" => {
373 for user in users {
374 writeln!(
375 &mut io::stdout(),
376 "{:?} => {:?}",
377 user.name(),
378 user.groups()
379 );
380 }
381 }
382 "boot_time" => {
383 writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384 }
385 "uptime" => {
386 let up = System::uptime();
387 let mut uptime = up;
388 let days = uptime / 86400;
389 uptime -= days * 86400;
390 let hours = uptime / 3600;
391 uptime -= hours * 3600;
392 let minutes = uptime / 60;
393 writeln!(
394 &mut io::stdout(),
395 "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396 );
397 }
398 x if x.starts_with("refresh") => {
399 if x == "refresh" {
400 writeln!(&mut io::stdout(), "Getting processes' information...");
401 sys.refresh_all();
402 writeln!(&mut io::stdout(), "Done.");
403 } else if x.starts_with("refresh ") {
404 writeln!(&mut io::stdout(), "Getting process' information...");
405 if let Some(pid) = x
406 .split(' ')
407 .filter_map(|pid| pid.parse().ok())
408 .take(1)
409 .next()
410 {
411 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412 writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413 } else {
414 writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415 }
416 } else {
417 writeln!(&mut io::stdout(), "Invalid [pid] received...");
418 }
419 } else {
420 writeln!(
421 &mut io::stdout(),
422 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423 list.",
424 );
425 }
426 }
427 "pid" => {
428 writeln!(
429 &mut io::stdout(),
430 "PID: {}",
431 sysinfo::get_current_pid().expect("failed to get PID")
432 );
433 }
434 "system" => {
435 writeln!(
436 &mut io::stdout(),
437 "System name: {}\n\
438 System kernel version: {}\n\
439 System OS version: {}\n\
440 System OS (long) version: {}\n\
441 System host name: {}",
442 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447 );
448 }
449 e => {
450 writeln!(
451 &mut io::stdout(),
452 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453 list.",
454 );
455 }
456 }
457 false
458}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.
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?
149fn interpret_input(
150 input: &str,
151 sys: &mut System,
152 networks: &mut Networks,
153 disks: &mut Disks,
154 components: &mut Components,
155 users: &mut Users,
156) -> bool {
157 match input.trim() {
158 "help" => print_help(),
159 "refresh_disks" => {
160 writeln!(&mut io::stdout(), "Refreshing disk list...");
161 disks.refresh(true);
162 writeln!(&mut io::stdout(), "Done.");
163 }
164 "refresh_users" => {
165 writeln!(&mut io::stdout(), "Refreshing user list...");
166 users.refresh();
167 writeln!(&mut io::stdout(), "Done.");
168 }
169 "refresh_networks" => {
170 writeln!(&mut io::stdout(), "Refreshing network list...");
171 networks.refresh(true);
172 writeln!(&mut io::stdout(), "Done.");
173 }
174 "refresh_components" => {
175 writeln!(&mut io::stdout(), "Refreshing component list...");
176 components.refresh(true);
177 writeln!(&mut io::stdout(), "Done.");
178 }
179 "refresh_cpu" => {
180 writeln!(&mut io::stdout(), "Refreshing CPUs...");
181 sys.refresh_cpu_all();
182 writeln!(&mut io::stdout(), "Done.");
183 }
184 "signals" => {
185 let mut nb = 1i32;
186
187 for sig in signals {
188 writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189 nb += 1;
190 }
191 }
192 "cpus" => {
193 // Note: you should refresh a few times before using this, so that usage statistics
194 // can be ascertained
195 writeln!(
196 &mut io::stdout(),
197 "number of physical cores: {}",
198 sys.physical_core_count()
199 .map(|c| c.to_string())
200 .unwrap_or_else(|| "Unknown".to_owned()),
201 );
202 writeln!(
203 &mut io::stdout(),
204 "total CPU usage: {}%",
205 sys.global_cpu_usage(),
206 );
207 for cpu in sys.cpus() {
208 writeln!(&mut io::stdout(), "{cpu:?}");
209 }
210 }
211 "memory" => {
212 writeln!(
213 &mut io::stdout(),
214 "total memory: {: >10} KB",
215 sys.total_memory() / 1_000
216 );
217 writeln!(
218 &mut io::stdout(),
219 "available memory: {: >10} KB",
220 sys.available_memory() / 1_000
221 );
222 writeln!(
223 &mut io::stdout(),
224 "used memory: {: >10} KB",
225 sys.used_memory() / 1_000
226 );
227 writeln!(
228 &mut io::stdout(),
229 "total swap: {: >10} KB",
230 sys.total_swap() / 1_000
231 );
232 writeln!(
233 &mut io::stdout(),
234 "used swap: {: >10} KB",
235 sys.used_swap() / 1_000
236 );
237 }
238 "quit" | "exit" => return true,
239 "all" => {
240 for (pid, proc_) in sys.processes() {
241 writeln!(
242 &mut io::stdout(),
243 "{}:{} status={:?}",
244 pid,
245 proc_.name().to_string_lossy(),
246 proc_.status()
247 );
248 }
249 }
250 "frequency" => {
251 for cpu in sys.cpus() {
252 writeln!(
253 &mut io::stdout(),
254 "[{}] {} MHz",
255 cpu.name(),
256 cpu.frequency(),
257 );
258 }
259 }
260 "vendor_id" => {
261 writeln!(
262 &mut io::stdout(),
263 "vendor ID: {}",
264 sys.cpus()[0].vendor_id()
265 );
266 }
267 "brand" => {
268 writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269 }
270 "load_avg" => {
271 let load_avg = System::load_average();
272 writeln!(&mut io::stdout(), "one minute : {}%", load_avg.one);
273 writeln!(&mut io::stdout(), "five minutes : {}%", load_avg.five);
274 writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275 }
276 e if e.starts_with("show ") => {
277 let tmp: Vec<&str> = e.split(' ').collect();
278
279 if tmp.len() != 2 {
280 writeln!(
281 &mut io::stdout(),
282 "show command takes a pid or a name in parameter!"
283 );
284 writeln!(&mut io::stdout(), "example: show 1254");
285 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286 match sys.process(pid) {
287 Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288 None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289 };
290 } else {
291 let proc_name = tmp[1];
292 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293 writeln!(
294 &mut io::stdout(),
295 "==== {} ====",
296 proc_.name().to_string_lossy()
297 );
298 writeln!(&mut io::stdout(), "{proc_:?}");
299 }
300 }
301 }
302 "temperature" => {
303 for component in components.iter() {
304 writeln!(&mut io::stdout(), "{component:?}");
305 }
306 }
307 "network" => {
308 for (interface_name, data) in networks.iter() {
309 writeln!(
310 &mut io::stdout(),
311 "{}:\n ether {}\n input data (new / total): {} / {} B\n output data (new / total): {} / {} B",
312 interface_name,
313 data.mac_address(),
314 data.received(),
315 data.total_received(),
316 data.transmitted(),
317 data.total_transmitted(),
318 );
319 }
320 }
321 "show" => {
322 writeln!(
323 &mut io::stdout(),
324 "'show' command expects a pid number or a process name"
325 );
326 }
327 e if e.starts_with("kill ") => {
328 let tmp: Vec<&str> = e.split(' ').collect();
329
330 if tmp.len() != 3 {
331 writeln!(
332 &mut io::stdout(),
333 "kill command takes the pid and a signal number in parameter!"
334 );
335 writeln!(&mut io::stdout(), "example: kill 1254 9");
336 } else {
337 let pid = Pid::from_str(tmp[1]).unwrap();
338 let signal = i32::from_str(tmp[2]).unwrap();
339
340 if signal < 1 || signal > 31 {
341 writeln!(
342 &mut io::stdout(),
343 "Signal must be between 0 and 32 ! See the signals list with the \
344 signals command"
345 );
346 } else {
347 match sys.process(pid) {
348 Some(p) => {
349 if let Some(res) =
350 p.kill_with(*signals.get(signal as usize - 1).unwrap())
351 {
352 writeln!(&mut io::stdout(), "kill: {res}");
353 } else {
354 writeln!(
355 &mut io::stdout(),
356 "kill: signal not supported on this platform"
357 );
358 }
359 }
360 None => {
361 writeln!(&mut io::stdout(), "pid not found");
362 }
363 };
364 }
365 }
366 }
367 "disks" => {
368 for disk in disks {
369 writeln!(&mut io::stdout(), "{disk:?}");
370 }
371 }
372 "users" => {
373 for user in users {
374 writeln!(
375 &mut io::stdout(),
376 "{:?} => {:?}",
377 user.name(),
378 user.groups()
379 );
380 }
381 }
382 "boot_time" => {
383 writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384 }
385 "uptime" => {
386 let up = System::uptime();
387 let mut uptime = up;
388 let days = uptime / 86400;
389 uptime -= days * 86400;
390 let hours = uptime / 3600;
391 uptime -= hours * 3600;
392 let minutes = uptime / 60;
393 writeln!(
394 &mut io::stdout(),
395 "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396 );
397 }
398 x if x.starts_with("refresh") => {
399 if x == "refresh" {
400 writeln!(&mut io::stdout(), "Getting processes' information...");
401 sys.refresh_all();
402 writeln!(&mut io::stdout(), "Done.");
403 } else if x.starts_with("refresh ") {
404 writeln!(&mut io::stdout(), "Getting process' information...");
405 if let Some(pid) = x
406 .split(' ')
407 .filter_map(|pid| pid.parse().ok())
408 .take(1)
409 .next()
410 {
411 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412 writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413 } else {
414 writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415 }
416 } else {
417 writeln!(&mut io::stdout(), "Invalid [pid] received...");
418 }
419 } else {
420 writeln!(
421 &mut io::stdout(),
422 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423 list.",
424 );
425 }
426 }
427 "pid" => {
428 writeln!(
429 &mut io::stdout(),
430 "PID: {}",
431 sysinfo::get_current_pid().expect("failed to get PID")
432 );
433 }
434 "system" => {
435 writeln!(
436 &mut io::stdout(),
437 "System name: {}\n\
438 System kernel version: {}\n\
439 System OS version: {}\n\
440 System OS (long) version: {}\n\
441 System host name: {}",
442 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447 );
448 }
449 e => {
450 writeln!(
451 &mut io::stdout(),
452 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453 list.",
454 );
455 }
456 }
457 false
458}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 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());
}
}Trait Implementations§
Auto Trait Implementations§
impl Freeze for Process
impl RefUnwindSafe for Process
impl Send for Process
impl Sync for Process
impl Unpin for Process
impl UnwindSafe for Process
Blanket Implementations§
§impl<T> Any for Twhere
T: 'static + ?Sized,
impl<T> Any for Twhere
T: 'static + ?Sized,
§impl<T> Borrow<T> for Twhere
T: ?Sized,
impl<T> Borrow<T> for Twhere
T: ?Sized,
§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T, U> Into<U> for Twhere
U: From<T>,
impl<T, U> Into<U> for Twhere
U: From<T>,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>where
F: FnOnce(&Self) -> bool,
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>where
F: FnOnce(&Self) -> bool,
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more