1 /*
2  * Copyright (c) 2023 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 HIVIEW_FRAMEWORK_NATIVE_UNIFIED_COLLECTION_PROCESS_PROCESS_STATUS_H
16 #define HIVIEW_FRAMEWORK_NATIVE_UNIFIED_COLLECTION_PROCESS_PROCESS_STATUS_H
17 
18 #include <mutex>
19 #include <unordered_map>
20 
21 #include "singleton.h"
22 
23 namespace OHOS {
24 namespace HiviewDFX {
25 namespace UCollectUtil {
26 enum ProcessState {
27     INVALID = -1,
28     BACKGROUND = 0,
29     FOREGROUND,
30     CREATED,
31     DIED,
32 };
33 
34 struct ProcessInfo {
35     std::string name;
36     ProcessState state;
37     uint64_t lastForegroundTime;
38 };
39 
40 class ProcessStatus : public OHOS::DelayedRefSingleton<ProcessStatus> {
41 public:
42     std::string GetProcessName(int32_t pid);
43     ProcessState GetProcessState(int32_t pid);
44     uint64_t GetProcessLastForegroundTime(int32_t pid);
45     void NotifyProcessState(int32_t pid, ProcessState procState);
46 
47 private:
48     bool UpdateProcessName(int32_t pid, const std::string& procName);
49     void UpdateProcessState(int32_t pid, ProcessState procState);
50     void UpdateProcessForegroundState(int32_t pid);
51     void UpdateProcessBackgroundState(int32_t pid);
52     bool NeedClearProcessInfos();
53     void ClearProcessInfos();
54     void ClearProcessInfo(int32_t pid);
55 
56 private:
57     std::mutex mutex_;
58     /* map<pid, ProcessInfo> */
59     std::unordered_map<int32_t, ProcessInfo> processInfos_;
60     uint32_t capacity_ = 1000; // 1000, max number of processes
61 };
62 } // namespace UCollectUtil
63 } // namespace HiviewDFX
64 } // namespace OHOS
65 #endif // HIVIEW_FRAMEWORK_NATIVE_UNIFIED_COLLECTION_PROCESS_PROCESS_STATUS_H
66