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 #include "kill_process.h"
16
17 #include <cstdint>
18 #include <csignal>
19 #include <sys/types.h>
20 #include "res_sched_errors.h"
21 #include "res_sched_log.h"
22
23 namespace OHOS {
24 namespace ResourceSchedule {
25 using namespace std;
26 namespace {
27 constexpr int32_t SIGNAL_KILL = 9;
28 }
29
KillProcessByPidWithClient(const nlohmann::json & payload,std::string killClientInitiator)30 int32_t KillProcess::KillProcessByPidWithClient(const nlohmann::json& payload, std::string killClientInitiator)
31 {
32 if ((payload == nullptr) || !(payload.contains("pid") && payload["pid"].is_string())) {
33 return RES_SCHED_KILL_PROCESS_FAIL;
34 }
35
36 pid_t pid = static_cast<int32_t>(atoi(payload["pid"].get<string>().c_str()));
37 if (pid == 0) {
38 return RES_SCHED_KILL_PROCESS_FAIL;
39 }
40 auto it = find(ALLOWED_CLIENT.begin(), ALLOWED_CLIENT.end(), killClientInitiator);
41 if (it == ALLOWED_CLIENT.end()) {
42 RESSCHED_LOGE("kill process fail, %{public}s no permission.", killClientInitiator.c_str());
43 return RES_SCHED_KILL_PROCESS_FAIL;
44 }
45
46 int32_t killRes = KillProcessByPid(pid);
47 if (killRes < 0) {
48 RESSCHED_LOGE("kill process %{public}d failed.", pid);
49 } else {
50 string processName = "unknown process";
51 if (payload.contains("processName") && payload["processName"].is_string()) {
52 processName = payload["processName"].get<string>();
53 }
54 RESSCHED_LOGI("kill process, killer is %{public}s, %{public}s to be killed, pid is %{public}d.",
55 killClientInitiator.c_str(), processName.c_str(), pid);
56 }
57 return killRes;
58 }
59
KillProcessByPid(const pid_t pid) const60 int32_t KillProcess::KillProcessByPid(const pid_t pid) const
61 {
62 int32_t ret = -1;
63 if (pid > 0) {
64 ret = kill(pid, SIGNAL_KILL);
65 RESSCHED_LOGI("kill pid %{public}d.", pid);
66 }
67 return ret;
68 }
69 } // namespace ResourceSchedule
70 } // namespace OHOS