| 117 | } |
| 118 | |
| 119 | Process::id_type Process::open(const std::function<void()> &function) noexcept { |
| 120 | if(open_stdin) |
| 121 | stdin_fd = std::unique_ptr<fd_type>(new fd_type); |
| 122 | if(read_stdout) |
| 123 | stdout_fd = std::unique_ptr<fd_type>(new fd_type); |
| 124 | if(read_stderr) |
| 125 | stderr_fd = std::unique_ptr<fd_type>(new fd_type); |
| 126 | |
| 127 | int stdin_p[2], stdout_p[2], stderr_p[2]; |
| 128 | |
| 129 | if(stdin_fd && pipe(stdin_p) != 0) |
| 130 | return -1; |
| 131 | if(stdout_fd && pipe(stdout_p) != 0) { |
| 132 | if(stdin_fd) { |
| 133 | close(stdin_p[0]); |
| 134 | close(stdin_p[1]); |
| 135 | } |
| 136 | return -1; |
| 137 | } |
| 138 | if(stderr_fd && pipe(stderr_p) != 0) { |
| 139 | if(stdin_fd) { |
| 140 | close(stdin_p[0]); |
| 141 | close(stdin_p[1]); |
| 142 | } |
| 143 | if(stdout_fd) { |
| 144 | close(stdout_p[0]); |
| 145 | close(stdout_p[1]); |
| 146 | } |
| 147 | return -1; |
| 148 | } |
| 149 | |
| 150 | id_type pid = fork(); |
| 151 | |
| 152 | if(pid < 0) { |
| 153 | if(stdin_fd) { |
| 154 | close(stdin_p[0]); |
| 155 | close(stdin_p[1]); |
| 156 | } |
| 157 | if(stdout_fd) { |
| 158 | close(stdout_p[0]); |
| 159 | close(stdout_p[1]); |
| 160 | } |
| 161 | if(stderr_fd) { |
| 162 | close(stderr_p[0]); |
| 163 | close(stderr_p[1]); |
| 164 | } |
| 165 | return pid; |
| 166 | } |
| 167 | else if(pid == 0) { |
| 168 | if(stdin_fd) |
| 169 | dup2(stdin_p[0], 0); |
| 170 | if(stdout_fd) |
| 171 | dup2(stdout_p[1], 1); |
| 172 | if(stderr_fd) |
| 173 | dup2(stderr_p[1], 2); |
| 174 | if(stdin_fd) { |
| 175 | close(stdin_p[0]); |
| 176 | close(stdin_p[1]); |