strat9_kernel/shell/commands/util/watch.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use super::*;
24
25/// Execute a command repeatedly at a given interval.
26///
27/// Usage: `watch <seconds> <command...>`
28///
29/// Runs the specified command every N seconds until Ctrl+C.
30pub fn cmd_watch(args: &[String]) -> Result<(), ShellError> {
31 if args.len() < 2 {
32 shell_println!("Usage: watch <seconds> <command...>");
33 return Err(ShellError::InvalidArguments);
34 }
35 let interval_secs: u64 = args[0].parse().map_err(|_| {
36 shell_println!("watch: invalid interval '{}'", args[0]);
37 ShellError::InvalidArguments
38 })?;
39 if interval_secs == 0 {
40 shell_println!("watch: interval must be >= 1 second");
41 return Err(ShellError::InvalidArguments);
42 }
43 let cmd_line = args[1..].join(" ");
44 let hz = crate::arch::timer::TIMER_HZ;
45 let interval_ticks = interval_secs * hz;
46
47 shell_println!("Every {}s: {}", interval_secs, cmd_line);
48 shell_println!("Press Ctrl+C to stop.\n");
49
50 loop {
51 if crate::shell::is_interrupted() {
52 break;
53 }
54 if let Some(ch) = crate::arch::keyboard::read_char() {
55 if ch == 0x03 || ch == b'q' {
56 break;
57 }
58 }
59
60 crate::shell::run_line(&cmd_line);
61
62 let start = crate::process::scheduler::ticks();
63 while crate::process::scheduler::ticks() - start < interval_ticks {
64 if crate::shell::is_interrupted() {
65 return Ok(());
66 }
67 if let Some(ch) = crate::arch::keyboard::read_char() {
68 if ch == 0x03 || ch == b'q' {
69 return Ok(());
70 }
71 }
72 crate::process::yield_task();
73 }
74 }
75 Ok(())
76}