Skip to content

Instantly share code, notes, and snippets.

@dulimarta
Last active September 24, 2020 03:17
Show Gist options
  • Save dulimarta/0f7ec79f0bd1c3954a39371d04198590 to your computer and use it in GitHub Desktop.
Save dulimarta/0f7ec79f0bd1c3954a39371d04198590 to your computer and use it in GitHub Desktop.
CS452 Lab03 - sample 3 (Rust)
use nix::unistd::{close, dup2, fork, pipe, ForkResult};
use std::io::{self, Read, Write};
use std::process::{exit, id};
use std::str;
use std::error::Error;
const MAX: usize = 1024;
fn main() -> Result<(),Box<dyn Error>> {
let mut buff = [0; MAX];
let (fd_in, fd_out) = pipe()?;
// point A
let result = fork();
// point B
match result {
Ok(ForkResult::Child) => {
dup2(fd_out, 1)?;
// point C
close(fd_in)?;
close(fd_out)?;
// point D
io::stdin().read(&mut buff)?;
io::stdout().write(&buff)?;
exit(0);
}
Ok(ForkResult::Parent { child: _pid }) => {
dup2(fd_in, 0)?;
close(fd_in)?;
close(fd_out)?;
io::stdin().read(&mut buff)?;
println!("By {}: {}", id(), str::from_utf8(&buff).unwrap());
}
Err(error) => {
println!("fork() error: {}", error);
exit(-1);
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment