process_utils.cc 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "chromecast/base/process_utils.h"
  5. #include <errno.h>
  6. #include <stddef.h>
  7. #include <stdio.h>
  8. #include "base/logging.h"
  9. #include "base/posix/safe_strerror.h"
  10. #include "base/strings/string_util.h"
  11. namespace chromecast {
  12. bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
  13. DCHECK(output);
  14. // Join the args into one string, creating the command.
  15. std::string command = base::JoinString(argv, " ");
  16. // Open the process.
  17. FILE* fp = popen(command.c_str(), "r");
  18. if (!fp) {
  19. LOG(ERROR) << "popen (" << command << ") failed: "
  20. << base::safe_strerror(errno);
  21. return false;
  22. }
  23. // Fill |output| with the stdout from the process.
  24. output->clear();
  25. while (!feof(fp)) {
  26. char buffer[256];
  27. size_t bytes_read = fread(buffer, 1, sizeof(buffer), fp);
  28. if (bytes_read <= 0)
  29. break;
  30. output->append(buffer, bytes_read);
  31. }
  32. // pclose() function waits for the associated process to terminate and returns
  33. // the exit status.
  34. return (pclose(fp) == 0);
  35. }
  36. } // namespace chromecast