nixd
Loading...
Searching...
No Matches
ForkPiped.cpp
Go to the documentation of this file.
2
3#include <cerrno>
4
5#include <system_error>
6#include <unistd.h>
7
8int nixd::forkPiped(int &In, int &Out, int &Err) {
9 static constexpr int READ = 0;
10 static constexpr int WRITE = 1;
11 int PipeIn[2];
12 int PipeOut[2];
13 int PipeErr[2];
14 if (pipe(PipeIn) == -1 || pipe(PipeOut) == -1 || pipe(PipeErr) == -1)
15 throw std::system_error(errno, std::generic_category());
16
17 pid_t Child = fork();
18
19 if (Child == 0) {
20 // Redirect stdin, stdout, stderr.
21 close(PipeIn[WRITE]);
22 close(PipeOut[READ]);
23 close(PipeErr[READ]);
24 dup2(PipeIn[READ], STDIN_FILENO);
25 dup2(PipeOut[WRITE], STDOUT_FILENO);
26 dup2(PipeErr[WRITE], STDERR_FILENO);
27 close(PipeIn[READ]);
28 close(PipeOut[WRITE]);
29 close(PipeErr[WRITE]);
30 // Child process.
31 return 0;
32 }
33
34 close(PipeIn[READ]);
35 close(PipeOut[WRITE]);
36 close(PipeErr[WRITE]);
37
38 if (Child == -1)
39 throw std::system_error(errno, std::generic_category());
40
41 In = PipeIn[WRITE];
42 Out = PipeOut[READ];
43 Err = PipeOut[READ];
44 return Child;
45}
int forkPiped(int &In, int &Out, int &Err)
fork this process and create some pipes connected to the new process.
Definition ForkPiped.cpp:8