shell_rs/
uptime.rs

1// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5use std::fs::File;
6use std::io::Read;
7
8use crate::error::Error;
9
10/// Tell how long the system has been running.
11/// Returns seconds since system bootup.
12pub fn uptime() -> Result<u64, Error> {
13    let mut fd = File::open("/proc/uptime")?;
14    let mut content = String::new();
15    fd.read_to_string(&mut content)?;
16    let idx = content.find(char::is_whitespace).unwrap_or(content.len());
17    let uptime_secs: f64 = content[0..idx].parse()?;
18    Ok(uptime_secs as u64)
19}
20
21#[cfg(test)]
22mod tests {
23    use super::uptime;
24
25    #[test]
26    fn test_uptime() {
27        let ret = uptime();
28        assert!(ret.is_ok());
29    }
30}