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

前端 未结 2 2143
余生分开走
余生分开走 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.

提交回复
热议问题