1 /*
2 * Copyright (c) 2023-2024 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 #include "kill_process.h"
16
17 #include <cstdint>
18 #include <sys/types.h>
19 #include "ability_manager_client.h"
20 #include "exit_reason.h"
21 #include "res_sched_errors.h"
22 #include "res_sched_exe_client.h"
23 #include "res_sched_kill_reason.h"
24 #include "res_sched_log.h"
25 #include "string_ex.h"
26
27 namespace OHOS {
28 namespace ResourceSchedule {
29 using namespace std;
30 namespace {
31 constexpr int32_t MAX_INDEX = 22;
32 constexpr int32_t START_TIME_INDEX = 19;
33 const std::string UNKNOWN_PROCESS = "unknown_process";
34 }
35
KillProcessByPidWithClient(const nlohmann::json & payload)36 int32_t KillProcess::KillProcessByPidWithClient(const nlohmann::json& payload)
37 {
38 if ((payload == nullptr) || !(payload.contains("pid") && payload["pid"].is_string())) {
39 return RES_SCHED_KILL_PROCESS_FAIL;
40 }
41
42 pid_t pid = static_cast<int32_t>(atoi(payload["pid"].get<string>().c_str()));
43 std::string processName = payload.contains("processName") && payload["processName"].is_string() ?
44 payload["processName"].get<string>() : UNKNOWN_PROCESS;
45 if (pid <= 0) {
46 RESSCHED_LOGE("process %{public}d:%{public}s is invalid", pid, processName.c_str());
47 return RES_SCHED_KILL_PROCESS_FAIL;
48 }
49 if (payload.contains("killReason") && payload["killReason"].is_string()) {
50 std::string killReason = payload["killReason"].get<string>();
51 AAFwk::ExitReason reason = {AAFwk::REASON_PERFORMANCE_CONTROL, killReason};
52 if (AAFwk::AbilityManagerClient::GetInstance()->RecordProcessExitReason(pid, reason) == 0) {
53 RESSCHED_LOGI("process %{public}d exitReason:%{public}s record success", pid, killReason.c_str());
54 } else {
55 RESSCHED_LOGE("process %{public}d exitReason:%{public}s record failed", pid, killReason.c_str());
56 }
57 }
58 int32_t killRes = ResSchedExeClient::GetInstance().KillProcess(pid);
59 if (killRes < 0) {
60 RESSCHED_LOGE("kill process %{public}d:%{public}s failed", pid, processName.c_str());
61 } else {
62 RESSCHED_LOGI("kill process %{public}d:%{public}s success", pid, processName.c_str());
63 }
64 return killRes;
65 }
66 } // namespace ResourceSchedule
67 } // namespace OHOS