Named pipes in Rust?


#1

I want to write a better clone of the ii irc client (https://tools.suckless.org/ii/) which uses named pipes for input and output.

I’ve written simple scripts that open a new terminal window, or tmux window, and splits the screen with tail -f the out pipe on the top, and vim the in pipe on the bottom to talk in a channel. It’s pretty nice, and I get things like history for free when running it on a server, along with being able to search through history, use vim, and so on.

I’ve been able to easily find IRC packages for Rust, but nothing for named pipes! Only “Windows named pipes” keep appearing. Maybe I’m not using the right term here, but I hope someone understands what I need.


#2

You can just open them with the standard std::fs::File API


#3

Right, but how do I create them?


#4

The easiest way is probably using libc::mkfifo.


#5

Nice. So I will have to use unsafe {} blocks to use this?


#6

Yes (but there’s nothing wrong with that here).


#7

nix just added mkfifo, which will give you a friendlier API than using libc directly. You’ll need to use the git version now, but we’re going to be making a new release soon.


#8

Good to know. I checked nix before recommending libc, but as you say, it’s only in git right now.


#9

Hello,

I have a question very similar to the previous one, so I try to post here before creating a new thread!

I tried to play with a named pipe in Rust, creating a new pipe and writing data into it using the standard file API, with this little piece of code:

extern crate libc;
use std::ffi::CString;

use std::fs::File;
use std::io::prelude::*;

fn main() {
    let path = "/tmp/test";
    let filename = CString::new(path.clone()).unwrap();
    unsafe {
        libc::mkfifo(filename.as_ptr(), 0o644);
    }

    println!("START");
    let mut f = File::open(&path).expect("file not found");
    println!("END");

    f.write_all("Hello, World!".as_bytes()).expect("failed");
}

But this code is wrong: the opening operation never ends up as if my current rust program was waiting for someone else to write something in the pipe.

What would be the proper way to proceed to write in a named pipe?

Thank you,


#10

Opening a named pipe for reading blocks until another process opens the same named pipe for writing, and vice versa. Do you have anything opening the same pipe in the other mode?


#11

No you’re right that’s exactly what I forgot … Thank you! It now seems obvious to me that it could not work asynchronously.