proc/
proc.rs

1use serde_::{Deserialize, Serialize};
2use std::env;
3use std::process;
4use unix_ipc::{channel, Bootstrapper, Receiver, Sender};
5
6const ENV_VAR: &str = "PROC_CONNECT_TO";
7
8#[derive(Serialize, Deserialize, Debug)]
9#[serde(crate = "serde_")]
10pub enum Task {
11    Sum(Vec<i64>, Sender<i64>),
12    Shutdown,
13}
14
15fn main() {
16    if let Ok(path) = env::var(ENV_VAR) {
17        let receiver = Receiver::<Task>::connect(path).unwrap();
18        loop {
19            let task = receiver.recv().unwrap();
20            match dbg!(task) {
21                Task::Sum(values, tx) => {
22                    tx.send(values.into_iter().sum::<i64>()).unwrap();
23                }
24                Task::Shutdown => break,
25            }
26        }
27    } else {
28        let bootstrapper = Bootstrapper::new().unwrap();
29        let mut child = process::Command::new(env::current_exe().unwrap())
30            .env(ENV_VAR, bootstrapper.path())
31            .spawn()
32            .unwrap();
33
34        let (tx, rx) = channel().unwrap();
35        bootstrapper.send(Task::Sum(vec![23, 42], tx)).unwrap();
36        println!("result: {}", rx.recv().unwrap());
37
38        let (tx, rx) = channel().unwrap();
39        bootstrapper.send(Task::Sum((0..10).collect(), tx)).unwrap();
40        println!("result: {}", rx.recv().unwrap());
41
42        bootstrapper.send(Task::Shutdown).unwrap();
43
44        child.kill().ok();
45        child.wait().ok();
46    }
47}