1 /*
2  * Copyright (C) 2015 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 
17 #ifndef SIMPLE_PERF_WORKLOAD_H_
18 #define SIMPLE_PERF_WORKLOAD_H_
19 
20 #include <sys/types.h>
21 #include <chrono>
22 #include <string>
23 #include <vector>
24 
25 #include <base/macros.h>
26 
27 class Workload {
28  private:
29   enum WorkState {
30     NotYetCreateNewProcess,
31     NotYetStartNewProcess,
32     Started,
33     Finished,
34   };
35 
36  public:
37   static std::unique_ptr<Workload> CreateWorkload(const std::vector<std::string>& args);
38 
~Workload()39   ~Workload() {
40     if (start_signal_fd_ != -1) {
41       close(start_signal_fd_);
42     }
43     if (exec_child_fd_ != -1) {
44       close(exec_child_fd_);
45     }
46   }
47 
48   bool Start();
49   bool IsFinished();
50   void WaitFinish();
GetPid()51   pid_t GetPid() {
52     return work_pid_;
53   }
54 
55  private:
Workload(const std::vector<std::string> & args)56   Workload(const std::vector<std::string>& args)
57       : work_state_(NotYetCreateNewProcess),
58         args_(args),
59         work_pid_(-1),
60         start_signal_fd_(-1),
61         exec_child_fd_(-1) {
62   }
63 
64   bool CreateNewProcess();
65   void WaitChildProcess(bool no_hang);
66 
67   WorkState work_state_;
68   std::vector<std::string> args_;
69   pid_t work_pid_;
70   int start_signal_fd_;  // The parent process writes 1 to start workload in the child process.
71   int exec_child_fd_;    // The child process writes 1 to notify that execvp() failed.
72 
73   DISALLOW_COPY_AND_ASSIGN(Workload);
74 };
75 
76 #endif  // SIMPLE_PERF_WORKLOAD_H_
77