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