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

前端 未结 2 2145
余生分开走
余生分开走 2021-02-19 03:48

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

相关标签:
2条回答
  • 2021-02-19 04:00

    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.

    0 讨论(0)
  • 2021-02-19 04:13

    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.

    0 讨论(0)
提交回复
热议问题