| 156 | #include <stdio.h> |
| 157 | |
| 158 | int read_command_output_through_popen(std::ostream& os, const char* cmd) { |
| 159 | FILE* pipe = popen(cmd, "r"); |
| 160 | if (pipe == NULL) { |
| 161 | return -1; |
| 162 | } |
| 163 | char buffer[1024]; |
| 164 | for (;;) { |
| 165 | size_t nr = fread(buffer, 1, sizeof(buffer), pipe); |
| 166 | if (nr != 0) { |
| 167 | os.write(buffer, nr); |
| 168 | } |
| 169 | if (nr != sizeof(buffer)) { |
| 170 | if (feof(pipe)) { |
| 171 | break; |
| 172 | } else if (ferror(pipe)) { |
| 173 | LOG(ERROR) << "Encountered error while reading for the pipe"; |
| 174 | break; |
| 175 | } |
| 176 | // retry; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | const int wstatus = pclose(pipe); |
| 181 | |
| 182 | if (wstatus < 0) { |
| 183 | return wstatus; |
| 184 | } |
| 185 | if (WIFEXITED(wstatus)) { |
| 186 | return WEXITSTATUS(wstatus); |
| 187 | } |
| 188 | if (WIFSIGNALED(wstatus)) { |
| 189 | os << "Child process was killed by signal " |
| 190 | << WTERMSIG(wstatus); |
| 191 | } |
| 192 | errno = ECHILD; |
| 193 | return -1; |
| 194 | } |
| 195 | |
| 196 | int read_command_output(std::ostream& os, const char* cmd) { |
| 197 | #if !defined(OS_LINUX) |
no outgoing calls