blob: 7956f0263db4c8c6bd48c674ef841facb20ba7c8 [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
7#include <base/basictypes.h>
Elly Jones1c4c3a12011-12-20 15:01:59 -05008#include <base/file_util.h>
Ben Chan5facf4a2014-07-23 16:36:54 -07009#include <base/files/file_path.h>
Ben Chan9953a592014-02-05 23:32:00 -080010#include <base/strings/string_split.h>
Elly Jones1c4c3a12011-12-20 15:01:59 -050011
12namespace debugd {
13
14ProcessWithOutput::ProcessWithOutput() : outfile_(NULL) { }
15ProcessWithOutput::~ProcessWithOutput() {
16 if (outfile_)
17 fclose(outfile_);
18 if (!outfile_path_.empty())
Ben Chan9953a592014-02-05 23:32:00 -080019 base::DeleteFile(outfile_path_, false); // not recursive
Elly Jones1c4c3a12011-12-20 15:01:59 -050020}
21
22bool ProcessWithOutput::Init() {
Elly Fong-Jonesd9a16cd2012-11-12 16:09:49 -050023 if (!SandboxedProcess::Init())
24 return false;
Ben Chan9953a592014-02-05 23:32:00 -080025 outfile_ = base::CreateAndOpenTemporaryFile(&outfile_path_);
Elly Jones1c4c3a12011-12-20 15:01:59 -050026 if (!outfile_)
27 return false;
28 // We can't just RedirectOutput to the file we just created, since
29 // RedirectOutput uses O_CREAT | O_EXCL to open the target file (i.e., it'll
30 // fail if the file already exists). We can't CreateTemporaryFile() and then
31 // use that filename, since we'd have to remove it before using
32 // RedirectOutput, which exposes us to a /tmp race. Instead, bind outfile_'s
33 // fd to the subprocess's stdout and stderr.
34 BindFd(fileno(outfile_), STDOUT_FILENO);
35 BindFd(fileno(outfile_), STDERR_FILENO);
36 return true;
37}
38
39bool ProcessWithOutput::GetOutputLines(std::vector<std::string>* output) {
40 std::string contents;
Ben Chan9953a592014-02-05 23:32:00 -080041 if (!base::ReadFileToString(outfile_path_, &contents))
Elly Jones1c4c3a12011-12-20 15:01:59 -050042 return false;
43 base::SplitString(contents, '\n', output);
44 return true;
45}
46
47bool ProcessWithOutput::GetOutput(std::string* output) {
Ben Chan9953a592014-02-05 23:32:00 -080048 return base::ReadFileToString(outfile_path_, output);
Elly Jones1c4c3a12011-12-20 15:01:59 -050049}
50
Ben Chana0011d82014-05-13 00:19:29 -070051} // namespace debugd