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