From 5b8d14413134daa7e0876995b34da319b1cb717b Mon Sep 17 00:00:00 2001 From: Thomas Hurst Date: Tue, 16 Nov 2021 04:31:44 +0000 Subject: [PATCH] Use /proc/self/stat on Linux (#3) --- src/linux.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/linux.rs b/src/linux.rs index e110c74..641b6b1 100644 --- a/src/linux.rs +++ b/src/linux.rs @@ -2,9 +2,13 @@ use std::fs; use std::num::NonZeroUsize; pub(crate) fn num_threads() -> Option { - fs::read_dir("/proc/self/task") - // If we can't read the directory, return `None`. + fs::read_to_string("/proc/self/stat") .ok() - // The number of files in the directory is the number of threads. - .and_then(|tasks| NonZeroUsize::new(tasks.count())) + .as_ref() + // Skip past the pid and (process name) fields + .and_then(|stat| stat.rsplit(')').next()) + // 20th field, less the two we skipped + .and_then(|rstat| rstat.split_whitespace().nth(17)) + .and_then(|num_threads| num_threads.parse::().ok()) + .and_then(NonZeroUsize::new) }