| 2025 | } |
| 2026 | |
| 2027 | inline std::pair<OutBuffer, ErrBuffer> |
| 2028 | Communication::communicate(const char* msg, size_t length) |
| 2029 | { |
| 2030 | // Optimization from subprocess.py |
| 2031 | // If we are using one pipe, or no pipe |
| 2032 | // at all, using select() or threads is unnecessary. |
| 2033 | auto hndls = {stream_->input(), stream_->output(), stream_->error()}; |
| 2034 | int count = std::count(std::begin(hndls), std::end(hndls), nullptr); |
| 2035 | const int len_conv = length; |
| 2036 | |
| 2037 | if (count >= 2) { |
| 2038 | OutBuffer obuf; |
| 2039 | ErrBuffer ebuf; |
| 2040 | if (stream_->input()) { |
| 2041 | if (msg) { |
| 2042 | int wbytes = std::fwrite(msg, sizeof(char), length, stream_->input()); |
| 2043 | if (wbytes < len_conv) { |
| 2044 | if (errno != EPIPE && errno != EINVAL) { |
| 2045 | throw OSError("fwrite error", errno); |
| 2046 | } |
| 2047 | } |
| 2048 | } |
| 2049 | // Close the input stream |
| 2050 | stream_->input_.reset(); |
| 2051 | } else if (stream_->output()) { |
| 2052 | // Read till EOF |
| 2053 | // ATTN: This could be blocking, if the process |
| 2054 | // at the other end screws up, we get screwed as well |
| 2055 | obuf.add_cap(out_buf_cap_); |
| 2056 | |
| 2057 | int rbytes = util::read_all( |
| 2058 | stream_->output(), |
| 2059 | obuf.buf); |
| 2060 | |
| 2061 | if (rbytes == -1) { |
| 2062 | throw OSError("read to obuf failed", errno); |
| 2063 | } |
| 2064 | |
| 2065 | obuf.length = rbytes; |
| 2066 | // Close the output stream |
| 2067 | stream_->output_.reset(); |
| 2068 | |
| 2069 | } else if (stream_->error()) { |
| 2070 | // Same screwness applies here as well |
| 2071 | ebuf.add_cap(err_buf_cap_); |
| 2072 | |
| 2073 | int rbytes = util::read_atmost_n( |
| 2074 | stream_->error(), |
| 2075 | ebuf.buf.data(), |
| 2076 | ebuf.buf.size()); |
| 2077 | |
| 2078 | if (rbytes == -1) { |
| 2079 | throw OSError("read to ebuf failed", errno); |
| 2080 | } |
| 2081 | |
| 2082 | ebuf.length = rbytes; |
| 2083 | // Close the error stream |
| 2084 | stream_->error_.reset(); |