| 156 | } |
| 157 | |
| 158 | bool SubProcess::Start() { |
| 159 | mutex_lock procLock(proc_mu_); |
| 160 | mutex_lock dataLock(data_mu_); |
| 161 | if (running_) { |
| 162 | LOG(ERROR) << "Start called after the process was started."; |
| 163 | return false; |
| 164 | } |
| 165 | if ((exec_path_ == nullptr) || (exec_argv_ == nullptr)) { |
| 166 | LOG(ERROR) << "Start called without setting a program."; |
| 167 | return false; |
| 168 | } |
| 169 | |
| 170 | // Create parent/child pipes for the specified channels and make the |
| 171 | // parent-side of the pipes non-blocking. |
| 172 | for (int i = 0; i < kNFds; i++) { |
| 173 | if (action_[i] == ACTION_PIPE) { |
| 174 | int pipe_fds[2]; |
| 175 | if (pipe(pipe_fds) < 0) { |
| 176 | LOG(ERROR) << "Start cannot create pipe: " << strerror(errno); |
| 177 | ClosePipes(); |
| 178 | return false; |
| 179 | } |
| 180 | // Handle the direction of the pipe (stdin vs stdout/err). |
| 181 | if (i == 0) { |
| 182 | parent_pipe_[i] = pipe_fds[1]; |
| 183 | child_pipe_[i] = pipe_fds[0]; |
| 184 | } else { |
| 185 | parent_pipe_[i] = pipe_fds[0]; |
| 186 | child_pipe_[i] = pipe_fds[1]; |
| 187 | } |
| 188 | |
| 189 | if (fcntl(parent_pipe_[i], F_SETFL, O_NONBLOCK) < 0) { |
| 190 | LOG(ERROR) << "Start cannot make pipe non-blocking: " |
| 191 | << strerror(errno); |
| 192 | ClosePipes(); |
| 193 | return false; |
| 194 | } |
| 195 | if (fcntl(parent_pipe_[i], F_SETFD, FD_CLOEXEC) < 0) { |
| 196 | LOG(ERROR) << "Start cannot make pipe close-on-exec: " |
| 197 | << strerror(errno); |
| 198 | ClosePipes(); |
| 199 | return false; |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // Start the child process and setup the file descriptors of both processes. |
| 205 | // See comment (1) in the header about issues with the use of fork(). |
| 206 | pid_ = fork(); |
| 207 | if (pid_ < 0) { |
| 208 | LOG(ERROR) << "Start cannot fork() child process: " << strerror(errno); |
| 209 | ClosePipes(); |
| 210 | return false; |
| 211 | } |
| 212 | |
| 213 | if (pid_ > 0) { |
| 214 | // Parent process: close the child-side pipes and return. |
| 215 | running_ = true; |