Created
January 10, 2017 13:48
-
-
Save aep/b11ceb7690ab9cdeadbe9429065d93d1 to your computer and use it in GitHub Desktop.
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
// this is a translation of https://github.com/aep/ceramic from C++ to rust | |
// | |
// since i'm new to rust asking for comments on how well this matches rust's design conventions | |
mod Ceramic { | |
extern crate nix; | |
use std::os::unix::io::RawFd; | |
use self::nix::unistd::ForkResult; | |
use self::nix::sys::socket; | |
use self::nix::unistd; | |
use std::process::exit; | |
pub struct Chan { | |
sync: (RawFd,RawFd), | |
data: (RawFd,RawFd), | |
} | |
impl Chan { | |
pub fn send(&self, buf: &[u8]) { | |
let mut void = [0;1]; | |
unistd::read (self.sync.0, &mut void); | |
unistd::write (self.data.0, buf); | |
} | |
pub fn recv(&self, buf: &mut [u8]) { | |
unistd::write (self.sync.1, &[0;1]); | |
unistd::read (self.data.1, buf); | |
} | |
pub fn new() -> Chan { | |
Chan { | |
sync: socket::socketpair(socket::AddressFamily::Unix, socket::SockType::Datagram, 0, socket::SockFlag::empty()).expect("socketpair failed"), | |
data: socket::socketpair(socket::AddressFamily::Unix, socket::SockType::Datagram, 0, socket::SockFlag::empty()).expect("socketpair failed"), | |
} | |
} | |
} | |
pub struct Proc { | |
} | |
impl Proc { | |
pub fn new<F>(start: F) -> Proc where F: Fn(){ | |
if let ForkResult::Child = nix::unistd::fork().expect("fork failed") { | |
start(); | |
exit(0); | |
}; | |
Proc{} | |
} | |
} | |
} | |
fn main() { | |
let chan = Ceramic::Chan::new(); | |
let thread = Ceramic::Proc::new(|| { | |
println!("child"); | |
chan.send(String::from("hello").as_bytes()); | |
}); | |
let mut buf = [0;128]; | |
chan.recv(&mut buf); | |
println!("parent received: {}", String::from_utf8_lossy(&buf)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment