1/*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15#ifndef HIPERF_TRACKED_COMMAND_H_
16#define HIPERF_TRACKED_COMMAND_H_
17
18#include <memory>
19#include <string>
20#include <utilities.h>
21namespace OHOS {
22namespace Developtools {
23namespace HiPerf {
24class TrackedCommand : public Noncopyable {
25public:
26    enum class State {
27        COMMAND_WAITING, // child process blocked to execute command
28        COMMAND_STARTED, // child process executing command
29        COMMAND_FAILURE, // command failed to start
30        COMMAND_STOPPED  // no child process or command execution
31    };
32
33    static std::unique_ptr<TrackedCommand> CreateInstance(const std::vector<std::string> &args);
34
35    ~TrackedCommand();
36
37    bool CreateChildProcess();
38    bool StartCommand();
39    bool WaitCommand(int &wstatus);
40    void Stop();
41
42    inline std::string GetCommandName()
43    {
44        if (!command_.empty()) {
45            return command_[0];
46        }
47        return EMPTY_STRING;
48    }
49
50    inline State GetState()
51    {
52        return state_;
53    }
54
55    inline pid_t GetChildPid()
56    {
57        return childPid_;
58    }
59
60private:
61    explicit TrackedCommand(const std::vector<std::string> &args);
62
63    bool InitSignalPipes(int &startFd, int &ackFd);
64    void ExecuteCommand(const int &startFd, const int &ackFd);
65    void MakeInvalid();
66
67    std::vector<std::string> command_ {};
68    int startFd_ {-1};
69    int ackFd_ {-1};
70    pid_t childPid_ {-1};
71    State state_ {State::COMMAND_STOPPED};
72};
73} // namespace HiPerf
74} // namespace Developtools
75} // namespace OHOS
76#endif // HIPERF_TRACKED_COMMAND_H_
77