• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17 
18 #include <memory>
19 #include <mutex>
20 #include <thread>
21 #include <vector>
22 
23 #include <common/libs/utils/subprocess.h>
24 
25 namespace cuttlefish {
26 
27 struct MonitorEntry;
28 using OnSocketReadyCb = std::function<bool(MonitorEntry*, int)>;
29 
30 struct MonitorEntry {
31   std::unique_ptr<Command> cmd;
32   std::unique_ptr<Subprocess> proc;
33 };
34 
35 // Keeps track of launched subprocesses, restarts them if they unexpectedly exit
36 class ProcessMonitor {
37  public:
38   ProcessMonitor(bool restart_subprocesses);
39   // Adds a command to the list of commands to be run and monitored. The
40   // callback will be called when the subprocess has ended.  If the callback
41   // returns false the subprocess will no longer be monitored. Can only be
42   // called before StartAndMonitorProcesses is called. OnSocketReadyCb will be
43   // called inside a forked process.
44   void AddCommand(Command cmd);
45   template <typename T>
AddCommands(T && commands)46   void AddCommands(T&& commands) {
47     for (auto& command : commands) {
48       AddCommand(std::move(command));
49     }
50   }
51 
52   // Start all processes given by AddCommand.
53   bool StartAndMonitorProcesses();
54   // Stops all monitored subprocesses.
55   bool StopMonitoredProcesses();
56  private:
57   bool MonitorRoutine();
58 
59   bool restart_subprocesses_;
60   std::vector<MonitorEntry> monitored_processes_;
61   pid_t monitor_;
62   SharedFD monitor_socket_;
63 };
64 }  // namespace cuttlefish
65