5274dba99dc48745c8b5c1fecae37f6d48607668
1 #include "ForkAndExec.hpp"
10 ForkAndExec::ForkAndExec(const char *binary_
, char **argv_
)
18 ForkAndExec::~ForkAndExec() {
19 for (auto &pipe
: {ready
, pipes
}) {
20 for (auto m
: {READ
, WRITE
}) {
26 int ForkAndExec::createPipe() {
27 if (pipes
[mode::READ
] == -1) {
28 if(pipe2(pipes
, O_NONBLOCK
)) {
29 perror("ForkAndExec pipe()");
34 return pipes
[mode::READ
];
37 pid_t
ForkAndExec::operator()() {
38 if (!prepareExecReadyPipe()) {
42 switch (pid_t pid
= fork()) {
44 closePipe(pipes
[mode::READ
]);
47 perror("ForkAndExec exec()");
51 perror("ForkAndExec fork()");
55 pipes
[mode::READ
] = -1;
56 closePipe(pipes
[mode::WRITE
]);
62 bool ForkAndExec::prepareExecReadyPipe() {
63 if (ready
[mode::READ
] == -1) {
64 if (pipe2(ready
, O_CLOEXEC
| O_NONBLOCK
)) {
65 perror("ForkAndExec pipe()");
68 closePipe(ready
[mode::WRITE
]);
74 void ForkAndExec::prepareOutputPipe() {
75 if (pipes
[mode::WRITE
] != -1) {
76 if (0 > dup2(pipes
[mode::WRITE
], STDERR_FILENO
) ||
77 0 > dup2(pipes
[mode::WRITE
], STDOUT_FILENO
)) {
78 perror("ForkAndExec dup()");
83 void ForkAndExec::closePipe(int &fd
) {
90 void ForkAndExec::pollExecReadyPipe() {
91 pollfd fd
{ready
[mode::READ
], 0, 0};
92 if (1 > poll(&fd
, 1, 5000)) {
93 cerr
<< "exec() timed out" << endl
;