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 <functional> 23 #include <string> 24 #include <vector> 25 26 #include <android-base/macros.h> 27 28 namespace simpleperf { 29 30 class Workload { 31 private: 32 enum WorkState { 33 NotYetCreateNewProcess, 34 NotYetStartNewProcess, 35 Started, 36 Finished, 37 }; 38 39 public: 40 static std::unique_ptr<Workload> CreateWorkload(const std::vector<std::string>& args); 41 static std::unique_ptr<Workload> CreateWorkload(const std::function<void()>& function); 42 static bool RunCmd(const std::vector<std::string>& args, bool report_error = true); 43 44 ~Workload(); 45 46 bool SetCpuAffinity(int cpu); 47 bool Start(); IsStarted()48 bool IsStarted() { return work_state_ == Started; } GetPid()49 pid_t GetPid() { return work_pid_; } 50 std::string GetCommandName(); 51 52 bool WaitChildProcess(bool wait_forever, int* exit_code); 53 54 // Set the function used to kill the workload process in ~Workload(). SetKillFunction(const std::function<void (pid_t)> & kill_function)55 void SetKillFunction(const std::function<void(pid_t)>& kill_function) { 56 kill_function_ = kill_function; 57 } 58 59 private: 60 explicit Workload(const std::vector<std::string>& args, const std::function<void()>& function); 61 62 bool CreateNewProcess(); 63 void ChildProcessFn(int start_signal_fd, int exec_child_fd); 64 bool WaitChildProcess(bool wait_forever, bool is_child_killed, int* exit_code); 65 66 WorkState work_state_; 67 // The child process either executes child_proc_args or run child_proc_function. 68 std::vector<std::string> child_proc_args_; 69 std::function<void()> child_proc_function_; 70 pid_t work_pid_; 71 int start_signal_fd_; // The parent process writes 1 to start workload in the child process. 72 int exec_child_fd_; // The child process writes 1 to notify that execvp() failed. 73 std::function<void(pid_t)> kill_function_; 74 75 DISALLOW_COPY_AND_ASSIGN(Workload); 76 }; 77 78 } // namespace simpleperf 79 80 #endif // SIMPLE_PERF_WORKLOAD_H_ 81