[][src]Function gaea::unix::new_pipe

pub fn new_pipe() -> Result<(Sender, Receiver)>

Create a new non-blocking unix pipe.

This is a wrapper around unix's pipe system call and can be used as interprocess communication channel.

This channel may be created before forking the process and then one end used in each process, e.g. the parent process has the sending end to send command to the child process.

Deregistering

Both Sender and Receiver will deregister themselves when dropped, iff the file descriptors are not duplicated (via dup(2)).

Examples

use std::io::{self, Read, Write};

use gaea::os::{OsQueue, RegisterOption};
use gaea::unix::{new_pipe, Sender, Receiver};
use gaea::{event, poll};

// Unique ids for the two ends of the channel.
const CHANNEL_RECV_ID: event::Id = event::Id(0);
const CHANNEL_SEND_ID: event::Id = event::Id(1);

// Create a `OsQueue` and the event sink.
let mut os_queue = OsQueue::new()?;
let mut events = Vec::new();

// Create a new pipe.
let (mut sender, mut receiver) = new_pipe()?;

// Register both ends of the channel.
os_queue.register(&mut receiver, CHANNEL_RECV_ID, Receiver::INTERESTS, RegisterOption::LEVEL)?;
os_queue.register(&mut sender, CHANNEL_SEND_ID, Sender::INTERESTS, RegisterOption::LEVEL)?;

const MSG: &[u8; 11] = b"Hello world";

loop {
    // Poll for events.
    poll::<_, io::Error>(&mut [&mut os_queue], &mut events, None)?;

    for event in &mut events {
        match event.id() {
            CHANNEL_SEND_ID => sender.write_all(MSG)?,
            CHANNEL_RECV_ID => {
                let mut buf = [0; 11];
                let n = receiver.read(&mut buf)?;
                println!("received: {:?}", &buf[0..n]);
            },
            _ => unreachable!(),
        }
    }
}