Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do interprocess communication (IPC) in Rust?

Tags:

rust

ipc

Is there part of the standard library for this?

I've been digging around, but I can't see anything immediately obvious that implements it, or anything on Process that would let you do this?

Did I miss it? Or do I have to do some C-wrapper work for this functionality?

(if so, is it 'safe' to serialize an object that is Send and pass it another process, then deserialize it there? That's what Send means right?)

like image 272
Doug Avatar asked Dec 29 '14 04:12

Doug


2 Answers

There is no single blessed way to do interprocess communication in Rust. You will need to use whatever technology you want: pipes, bare sockets (TCP or UDP), shared memory, nanomsg/ZeroMQ, whatever.

Also Send does not mean that you can serialize an object of a type which implements it and send to another process. It means that the data can be safely sent to another thread (e.g. it does not contain any references into the stack of the source thread), and it is not related to serialization.

For example, one of the basic forms of IPC are stdin/stdout pipes between parent and child processes. Process API allows you to send and receive data through these pipes:

use std::io::process::Command;

fn main() {
    let mut p = Command::new("tr").arg("a-z").arg("A-Z").spawn().unwrap();

    {
        let mut p_stdin = p.stdin.as_mut().unwrap();
        p_stdin.write_str("hello world").unwrap();
    }
    p.wait().unwrap().success();

    let response = p.stdout.as_mut().unwrap().read_to_string().unwrap();
    println!("Responded: {}", response);
}

Or you can use sockets, but the example would be quite large. You can find sockets API documentation here.

like image 120
Vladimir Matveev Avatar answered Oct 14 '22 09:10

Vladimir Matveev


I recommend you look at the plibsys library. A trivial bindgen binding is available as a starting point for anyone who wants to write an idiomatic Rust binding.

If all you're after is simple, practical IPC in Rust, falling back to the C IPC mechanisms is currently the only real solution; plibsys is simply a convenient portable high level C API to do that with.

like image 20
Doug Avatar answered Oct 14 '22 09:10

Doug