Last active
September 24, 2020 03:17
-
-
Save dulimarta/0f7ec79f0bd1c3954a39371d04198590 to your computer and use it in GitHub Desktop.
CS452 Lab03 - sample 3 (Rust)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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