blob: 7f56ad5e8b79125a7b099903aa3faa1b48ff6146 [file] [log] [blame]
Elly Jonesa44d22d2012-01-05 18:05:56 -05001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Elly Jones1c4c3a12011-12-20 15:01:59 -05002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Alex Vakulenko262be3f2014-07-30 15:25:50 -07005#include "debugd/src/process_with_output.h"
Elly Jones1c4c3a12011-12-20 15:01:59 -05006
Ben Chan5facf4a2014-07-23 16:36:54 -07007#include <base/files/file_path.h>
Ben Chancd8fda42014-09-05 08:21:06 -07008#include <base/files/file_util.h>
Ben Chan9953a592014-02-05 23:32:00 -08009#include <base/strings/string_split.h>
Elly Jones1c4c3a12011-12-20 15:01:59 -050010
11namespace debugd {
12
Ben Chan78f89532014-08-29 09:35:09 -070013ProcessWithOutput::ProcessWithOutput() : outfile_(NULL) {}
14
Elly Jones1c4c3a12011-12-20 15:01:59 -050015ProcessWithOutput::~ProcessWithOutput() {
16 if (outfile_)
17 fclose(outfile_);
Ben Chan78f89532014-08-29 09:35:09 -070018
Elly Jones1c4c3a12011-12-20 15:01:59 -050019 if (!outfile_path_.empty())
Ben Chan9953a592014-02-05 23:32:00 -080020 base::DeleteFile(outfile_path_, false); // not recursive
Elly Jones1c4c3a12011-12-20 15:01:59 -050021}
22
23bool ProcessWithOutput::Init() {
Elly Fong-Jonesd9a16cd2012-11-12 16:09:49 -050024 if (!SandboxedProcess::Init())
25 return false;
Ben Chan78f89532014-08-29 09:35:09 -070026
Ben Chan9953a592014-02-05 23:32:00 -080027 outfile_ = base::CreateAndOpenTemporaryFile(&outfile_path_);
Elly Jones1c4c3a12011-12-20 15:01:59 -050028 if (!outfile_)
29 return false;
Ben Chan78f89532014-08-29 09:35:09 -070030
Elly Jones1c4c3a12011-12-20 15:01:59 -050031 // We can't just RedirectOutput to the file we just created, since
32 // RedirectOutput uses O_CREAT | O_EXCL to open the target file (i.e., it'll
33 // fail if the file already exists). We can't CreateTemporaryFile() and then
34 // use that filename, since we'd have to remove it before using
35 // RedirectOutput, which exposes us to a /tmp race. Instead, bind outfile_'s
36 // fd to the subprocess's stdout and stderr.
37 BindFd(fileno(outfile_), STDOUT_FILENO);
38 BindFd(fileno(outfile_), STDERR_FILENO);
39 return true;
40}
41
42bool ProcessWithOutput::GetOutputLines(std::vector<std::string>* output) {
43 std::string contents;
Ben Chan9953a592014-02-05 23:32:00 -080044 if (!base::ReadFileToString(outfile_path_, &contents))
Elly Jones1c4c3a12011-12-20 15:01:59 -050045 return false;
Ben Chan78f89532014-08-29 09:35:09 -070046
Elly Jones1c4c3a12011-12-20 15:01:59 -050047 base::SplitString(contents, '\n', output);
48 return true;
49}
50
51bool ProcessWithOutput::GetOutput(std::string* output) {
Ben Chan9953a592014-02-05 23:32:00 -080052 return base::ReadFileToString(outfile_path_, output);
Elly Jones1c4c3a12011-12-20 15:01:59 -050053}
54
Ben Chana0011d82014-05-13 00:19:29 -070055} // namespace debugd