-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathexample.cpp
72 lines (65 loc) · 2.1 KB
/
example.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <filesystem>
#include <fstream>
#include <future>
#include <init.capnp.h>
#include <init.capnp.proxy.h>
#include <iostream>
#include <mp/proxy-io.h>
#include <mp/util.h>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
namespace fs = std::filesystem;
static auto Spawn(mp::EventLoop& loop, const std::string& process_argv0, const std::string& new_exe_name)
{
int pid;
const int fd = mp::SpawnProcess(pid, [&](int fd) -> std::vector<std::string> {
fs::path path = process_argv0;
path.remove_filename();
path.append(new_exe_name);
return {path.string(), std::to_string(fd)};
});
return std::make_tuple(mp::ConnectStream<InitInterface>(loop, fd), pid);
}
static void LogPrint(bool raise, const std::string& message)
{
if (raise) throw std::runtime_error(message);
std::ofstream("debug.log", std::ios_base::app) << message << std::endl;
}
int main(int argc, char** argv)
{
if (argc != 1) {
std::cout << "Usage: mpexample\n";
return 1;
}
std::promise<mp::EventLoop*> promise;
std::thread loop_thread([&] {
mp::EventLoop loop("mpexample", LogPrint);
promise.set_value(&loop);
loop.loop();
});
mp::EventLoop* loop = promise.get_future().get();
auto [printer_init, printer_pid] = Spawn(*loop, argv[0], "mpprinter");
auto [calc_init, calc_pid] = Spawn(*loop, argv[0], "mpcalculator");
auto calc = calc_init->makeCalculator(printer_init->makePrinter());
while (true) {
std::string eqn;
std::cout << "Enter the equation, or \"exit\" to quit: ";
std::getline(std::cin, eqn);
if (eqn == "exit") break;
calc->solveEquation(eqn);
}
calc.reset();
calc_init.reset();
mp::WaitProcess(calc_pid);
printer_init.reset();
mp::WaitProcess(printer_pid);
loop_thread.join();
std::cout << "Bye!" << std::endl;
return 0;
}