1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "ServiceDescriptor.h" 18 19 #include <array> 20 #include <memory> 21 22 #include <stdio.h> 23 #include <stdlib.h> 24 #include <string.h> 25 26 ServiceDescriptor::ServiceDescriptor(std::string name, std::string cmd) 27 : mName(name), mCommandLine(cmd) {} 28 29 std::optional<std::string> ServiceDescriptor::GetOutput(OutputConsumer* consumer) const { 30 if (!IsAvailable()) return "service not available"; 31 32 const auto cmd = command(); 33 34 int commandExitStatus = 0; 35 auto pipeStreamDeleter = [&commandExitStatus](std::FILE* fp) { 36 commandExitStatus = pclose(fp); 37 }; 38 std::unique_ptr<std::FILE, decltype(pipeStreamDeleter)> pipeStream(popen(cmd, "r"), 39 pipeStreamDeleter); 40 41 if (!pipeStream) { 42 return std::string("Failed to execute ") + cmd + ", " + strerror(errno); 43 } 44 45 std::array<char, 65536> buffer; 46 while (!std::feof(pipeStream.get())) { 47 auto readLen = fread(buffer.data(), 1, buffer.size(), pipeStream.get()); 48 consumer->Write(buffer.data(), readLen); 49 } 50 51 pipeStream.reset(); 52 53 if (commandExitStatus == 0) { 54 return std::nullopt; 55 } else if (commandExitStatus < 0) { 56 return std::string("Failed when pclose ") + cmd + ", " + strerror(errno); 57 } else { 58 return std::string("Error when executing ") + cmd + 59 ", exit code: " + std::to_string(commandExitStatus); 60 } 61 } 62