Debian Codegraph @

debian/rust-vendor/procfs/examples/lslocks.rs

raw
1 use procfs::process::{FDTarget, Process};
2 use rustix::fs::AtFlags;
3 use std::path::Path;
4
5 fn main() {
6 let myself = Process::myself().unwrap();
7 let mountinfo = myself.mountinfo().unwrap();
8 println!("{:18}{:13}{:13}{:13}{:12} Path", "Process", "PID", "Lock Type", "Mode", "Kind");
9 println!("{}", "=".repeat(74));
10 for lock in procfs::locks().unwrap() {
11 lock.pid
12 .and_then(|pid| Process::new(pid).ok())
13 .and_then(|proc| proc.cmdline().ok())
14 .and_then(|mut cmd| cmd.drain(..).next())
15 .map_or_else(
16 || {
17 print!("{:18}", "(undefined)");
18 },
19 |s| {
20 let p = Path::new(&s);
21 print!("{:18}", p.file_name().unwrap_or(p.as_os_str()).to_string_lossy());
22 },
23 );
24
25 print!("{:<12} ", lock.pid.unwrap_or(-1));
26 print!("{:12} ", lock.lock_type.as_str());
27 print!("{:12} ", lock.mode.as_str());
28 print!("{:12} ", lock.kind.as_str());
29
30 // try to find the path for this inode
31 let mut found = false;
32 if let Some(pid) = lock.pid {
33 if let Ok(fds) = Process::new(pid).and_then(|p| p.fd()) {
34 for f in fds {
35 let fd = f.unwrap();
36 if let FDTarget::Path(p) = fd.target {
37 if let Ok(stat) = rustix::fs::statat(&rustix::fs::CWD, &p, AtFlags::empty()) {
38 if stat.st_ino as u64 == lock.inode {
39 print!("{}", p.display());
40 found = true;
41 break;
42 }
43 }
44 }
45 }
46 }
47 }
48
49 if !found {
50 // we don't have a PID or we don't have permission to inspect the processes files, but we still have the device and inode
51 // There's no way to look up a path from an inode, so just bring the device mount point
52 for mount in &mountinfo {
53 if format!("{}:{}", lock.devmaj, lock.devmin) == mount.majmin {
54 print!("{}...", mount.mount_point.display());
55 found = true;
56 break;
57 }
58 }
59 }
60
61 if !found {
62 // still not found? print the device
63 print!("{}:{}", lock.devmaj, lock.devmin);
64 }
65
66 println!();
67 }
68 }