I'm trying to execute a 'less' command in my rust command line application.
Example
In fact, I want the same behavior as git-diff
. For instance:
The command...
$ git diff file.ext
... opens less (or pager configured in environment variables) ...
diff --git ...
# the actual diff
.. All pager commands are usable (vim-like moves for example),
and pressing q
quit the pager and returns to terminal prompt ...
$ git diff file.ext
$ █
... git-diff
command ends (return code 0
).
Code
This is what I tried for my cla
(Command Line Application):
Rust Playground: Playground
source:
use std::path::Path;
pub fn main() {
let path = Path::new("/proc/cpuinfo");
std::process::Command::new("less")
.arg(path.as_os_str())
.spawn()
.expect("command failed");
}
run:
$ cargo build --release
$ target/release/cla
$ █
The program just runs and returns exit code 0
but less is not opened.
How am I supposed to spawn a less command in my terminal ?
Thanks
Solution
The code needs to wait for child process otherwise the program won't wait until less command exits:
use std::path::Path;
pub fn main() {
let path = Path::new("/proc/cpuinfo");
std::process::Command::new("less")
.arg(path.as_os_str())
.spawn()
.expect("command failed")
.wait()
.expect("wait failed");
}