Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::process::{Child, Command, Stdio};
- use std::os::unix::prelude::*;
- use std::fs::File;
- use std::io;
- struct Redirect {
- pager: Child,
- }
- fn redirect_stdout() -> io::Result<Redirect> {
- let mut pager = Command::new("less")
- .stdin(Stdio::piped())
- .arg("-FR")
- .spawn()?;
- let stdin = pager.stdin.take().unwrap();
- unsafe {
- // redirect our stdout/stderr to the `less` child process
- if libc::dup2(stdin.as_raw_fd(), libc::STDOUT_FILENO) < 0 {
- return Err(io::Error::last_os_error())
- }
- if libc::dup2(stdin.as_raw_fd(), libc::STDERR_FILENO) < 0 {
- return Err(io::Error::last_os_error())
- }
- }
- Ok(Redirect { pager })
- }
- impl Drop for Redirect {
- fn drop(&mut self) {
- unsafe {
- let null = File::open("/dev/null").unwrap();
- // "close" stdio streams now that our program is done
- assert!(libc::dup2(null.as_raw_fd(), libc::STDIN_FILENO) >= 0);
- assert!(libc::dup2(null.as_raw_fd(), libc::STDOUT_FILENO) >= 0);
- assert!(libc::dup2(null.as_raw_fd(), libc::STDERR_FILENO) >= 0);
- }
- self.pager.wait().unwrap();
- }
- }
- fn main() {
- let _pager = redirect_stdout().unwrap();
- for i in 0..100 {
- println!("wut: {}", i);
- }
- }
Add Comment
Please, Sign In to add comment