cap_primitives/rustix/linux/fs/
file_path.rs

1use super::procfs::get_path_from_proc_self_fd;
2use std::fs;
3use std::path::PathBuf;
4
5pub(crate) fn file_path(file: &fs::File) -> Option<PathBuf> {
6    use std::os::unix::fs::MetadataExt;
7
8    // Ignore paths that don't start with '/', which are things like
9    // `socket:[3556564]` or similar.
10    let path = get_path_from_proc_self_fd(file)
11        .ok()
12        .filter(|path| path.starts_with("/"))?;
13
14    // Linux appends the string " (deleted)" when a file is deleted; avoid
15    // treating that as the actual name. Check this after doing the `readlink`
16    // above so that we're conservative about concurrent deletions.
17    if file.metadata().ok()?.nlink() == 0 {
18        return None;
19    }
20
21    Some(path)
22}