Skip to content

Commit 950b464

Browse files
committed
top: implement VIRT RES SHR
1 parent cc9c335 commit 950b464

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/uu/top/src/picker.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ pub(crate) fn pickers(fields: &[String]) -> Vec<Box<dyn Fn(u32) -> String>> {
2727
"USER" => helper(user),
2828
"PR" => helper(pr),
2929
"NI" => helper(ni),
30+
"VIRT" => helper(virt),
3031
"RES" => helper(res),
3132
"SHR" => helper(shr),
3233
"S" => helper(s),
@@ -44,6 +45,16 @@ fn helper(f: impl Fn(u32) -> String + 'static) -> Box<dyn Fn(u32) -> String> {
4445
Box::new(f)
4546
}
4647

48+
#[cfg(target_os = "linux")]
49+
fn format_memory(memory_b: f64) -> String {
50+
let mem_mb = memory_b / bytesize::MIB as f64;
51+
if mem_mb >= 10000.0 {
52+
format!("{:.1}g", memory_b / bytesize::GIB as f64)
53+
} else {
54+
format!("{mem_mb:.1}m")
55+
}
56+
}
57+
4758
fn todo(_pid: u32) -> String {
4859
"TODO".into()
4960
}
@@ -133,10 +144,51 @@ fn ni(_pid: u32) -> String {
133144
"0".into()
134145
}
135146

147+
#[cfg(target_os = "linux")]
148+
fn virt(pid: u32) -> String {
149+
let binding = sysinfo().read().unwrap();
150+
let Some(proc) = binding.process(Pid::from_u32(pid)) else {
151+
return "0.0".into();
152+
};
153+
format_memory(proc.virtual_memory() as f64)
154+
}
155+
156+
#[cfg(not(target_os = "linux"))]
157+
fn virt(_pid: u32) -> String {
158+
"TODO".into()
159+
}
160+
161+
#[cfg(target_os = "linux")]
162+
fn res(pid: u32) -> String {
163+
let binding = sysinfo().read().unwrap();
164+
let Some(proc) = binding.process(Pid::from_u32(pid)) else {
165+
return "0.0".into();
166+
};
167+
format_memory(proc.memory() as f64)
168+
}
169+
170+
#[cfg(not(target_os = "linux"))]
136171
fn res(_pid: u32) -> String {
137172
"TODO".into()
138173
}
139174

175+
#[cfg(target_os = "linux")]
176+
fn shr(pid: u32) -> String {
177+
let file_path = format!("/proc/{pid}/statm");
178+
let Ok(file) = File::open(file_path) else {
179+
return "0.0".into();
180+
};
181+
let content = read_to_string(file).unwrap();
182+
let values = content.split_whitespace();
183+
if let Some(shared) = values.collect::<Vec<_>>().get(2) {
184+
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
185+
format_memory(shared.parse::<u64>().unwrap() as f64 * page_size as f64)
186+
} else {
187+
"0.0".into()
188+
}
189+
}
190+
191+
#[cfg(not(target_os = "linux"))]
140192
fn shr(_pid: u32) -> String {
141193
"TODO".into()
142194
}

0 commit comments

Comments
 (0)