Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
process.cpp
Go to the documentation of this file.
1#include "process.hpp"
2#include <cstring>
3
4Process::Process(const std::string& command)
5{
6 int stdin_pipe[2]; // NOLINT
7 int stdout_pipe[2]; // NOLINT
8 pid_t pid = 0;
9
10 if (pipe(stdin_pipe) < 0 || pipe(stdout_pipe) < 0) {
11 throw std::runtime_error("pipe() failed");
12 }
13
14 pid = fork();
15 if (pid < 0) {
16 throw std::runtime_error("fork() failed");
17 }
18
19 if (pid == 0) { // Child process
20 close(stdin_pipe[1]);
21 close(stdout_pipe[0]);
22
23 dup2(stdin_pipe[0], STDIN_FILENO);
24 dup2(stdout_pipe[1], STDOUT_FILENO);
25
26 close(stdin_pipe[0]);
27 close(stdout_pipe[1]);
28
29 execl("/bin/sh", "sh", "-c", command.c_str(), nullptr); // NOLINT
30 exit(1);
31 }
32
33 // Parent process
34 close(stdin_pipe[0]);
35 close(stdout_pipe[1]);
36
37 this->pid = pid;
38 this->stdin_fd = stdin_pipe[1];
39 this->stdout_fd = stdout_pipe[0];
40}
41
43{
44 close(stdin_fd);
45 close(stdout_fd);
46 waitpid(pid, nullptr, 0);
47}
48
49void Process::write_line(const std::string& line) const
50{
51 std::string command = line + "\n";
52 write(stdin_fd, command.c_str(), command.size());
53 fsync(stdin_fd);
54}
55
56std::string Process::read_line() const
57{
58 char buffer[4096]; // NOLINT
59 std::string response;
60 ssize_t bytes_read = 0;
61 fsync(stdout_fd);
62 while ((bytes_read = read(stdout_fd, buffer, sizeof(buffer))) > 0) {
63 response.append(buffer, static_cast<size_t>(bytes_read));
64 if (response.find('\n') != std::string::npos) {
65 break;
66 }
67 }
68 if (bytes_read < 0 && errno != EINTR) {
69 throw std::runtime_error("read() error: " + std::string(std::strerror(errno)));
70 }
71 return response;
72}
std::string read_line() const
Reads a line from the process.
Definition process.cpp:56
pid_t pid
Definition process.hpp:10
Process(const std::string &command)
Definition process.cpp:4
void write_line(const std::string &line) const
Ends line with a newline character, sends to the process.
Definition process.cpp:49
~Process()
Definition process.cpp:42
int stdin_fd
Definition process.hpp:11
int stdout_fd
Definition process.hpp:12
uint8_t buffer[RANDOM_BUFFER_SIZE]
Definition engine.cpp:34
void write(const T t)
Definition g1.test.cpp:409
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13