blob: bdf112419dcc12629aaec45ed83cadcfe7cd0b9e [file] [log] [blame]
Elly Jones1c4c3a12011-12-20 15:01:59 -05001// Copyright (c) 2011 The Chromium OS 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
5#include "process_with_output.h"
6
7#include <base/basictypes.h>
8#include <base/file_path.h>
9#include <base/file_util.h>
10#include <base/string_split.h>
11
12namespace debugd {
13
14ProcessWithOutput::ProcessWithOutput() : outfile_(NULL) { }
15ProcessWithOutput::~ProcessWithOutput() {
16 if (outfile_)
17 fclose(outfile_);
18 if (!outfile_path_.empty())
19 file_util::Delete(outfile_path_, false); // not recursive
20}
21
22bool ProcessWithOutput::Init() {
23 outfile_ = file_util::CreateAndOpenTemporaryFile(&outfile_path_);
24 if (!outfile_)
25 return false;
26 // We can't just RedirectOutput to the file we just created, since
27 // RedirectOutput uses O_CREAT | O_EXCL to open the target file (i.e., it'll
28 // fail if the file already exists). We can't CreateTemporaryFile() and then
29 // use that filename, since we'd have to remove it before using
30 // RedirectOutput, which exposes us to a /tmp race. Instead, bind outfile_'s
31 // fd to the subprocess's stdout and stderr.
32 BindFd(fileno(outfile_), STDOUT_FILENO);
33 BindFd(fileno(outfile_), STDERR_FILENO);
34 return true;
35}
36
37bool ProcessWithOutput::GetOutputLines(std::vector<std::string>* output) {
38 std::string contents;
39 if (!file_util::ReadFileToString(outfile_path_, &contents))
40 return false;
41 base::SplitString(contents, '\n', output);
42 return true;
43}
44
45bool ProcessWithOutput::GetOutput(std::string* output) {
46 return file_util::ReadFileToString(outfile_path_, output);
47}
48
49}; // namespace debugd