blob: 8b41c240809508a23da06eae241b0d7fcd2d87a2 [file] [log] [blame]
Piotr Pawliczekc3ff7da2020-06-26 14:23:56 -07001// Copyright 2020 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#ifndef FOOMATIC_SHELL_PROCESS_LAUNCHER_H_
6#define FOOMATIC_SHELL_PROCESS_LAUNCHER_H_
7
8#include <sys/types.h>
9
10#include <memory>
11#include <set>
12#include <string>
13
14#include "foomatic_shell/grammar.h"
15
16namespace brillo {
17class Process;
18}
19
20namespace foomatic_shell {
21
22// Exit code reported when an error occurs of the shell side.
23constexpr int kShellError = 127;
24
25// This class is responsible for executing given Script object. It launches
26// all commands and subshells from the Script in a correct order and join them
27// with pipes. All errors are reported to standard error stream.
28class ProcessLauncher {
29 public:
30 // Constructor. |source| is a reference to original sources of executed
31 // script and it must be constant and valid during the lifetime of the
32 // object. |source| is used only for building error messages.
33 // |verbose_mode| activates additional logs on stderr.
34 explicit ProcessLauncher(const std::string& source, bool verbose_mode)
35 : source_(source), verbose_(verbose_mode) {}
36
37 // This method executes the given |script|. A file descriptor |input_fd| is
38 // connected as a standard input stream for executed script, while a file
39 // descriptor |output_fd| is connected as a standard output stream. The
40 // execution is stopped on the first failing pipeline. The method returns
41 // exit code of the last executed pipeline. Only zero guarantees that the
42 // whole script was executed.
43 int RunScript(const Script& script, int input_fd, int output_fd);
44
45 private:
46 // Helper methods.
47 int RunPipeline(const Pipeline& pipeline, int input_fd, int output_fd);
48 std::unique_ptr<brillo::Process> StartProcess(const Command& command,
49 int input_fd,
50 int output_fd);
51 pid_t StartSubshell(const Script& script,
52 int input_fd,
53 int output_fd,
54 std::set<int> open_fds);
55
56 // This field holds the reference to the script's source provided in the
57 // constructor.
58 const std::string& source_;
59 // This field enables additional logging.
60 bool verbose_;
61};
62
63} // namespace foomatic_shell
64
65#endif // FOOMATIC_SHELL_PROCESS_LAUNCHER_H_