1 /*
2 * Copyright (c) 2021 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
16 #include <chrono>
17 #include <assert.h>
18 #include <signal.h>
19 #include <sys/prctl.h>
20 #include "watchdog.h"
21
22 namespace OHOS::Camera {
23
WatchDog()24 WatchDog::WatchDog() {}
25
Init(int ms,std::function<void ()> executor,bool isKill)26 void WatchDog::Init(int ms, std::function<void()> executor, bool isKill)
27 {
28 timeMs_ = ms;
29 isKill_ = isKill;
30 executor_ = executor;
31 handleThread_ = std::make_unique<std::thread>(&WatchDog::WaitForWakeUP, this);
32 }
33
~WatchDog()34 WatchDog::~WatchDog()
35 {
36 {
37 std::unique_lock<std::mutex> l(lock_);
38 terminate_ = true;
39 cv_.notify_one();
40 }
41 if (handleThread_ != nullptr && handleThread_->joinable()) {
42 handleThread_->join();
43 }
44 }
45
WaitForWakeUP()46 void WatchDog::WaitForWakeUP()
47 {
48 prctl(PR_SET_NAME, "camera_watchdog");
49
50 std::unique_lock<std::mutex> l(lock_);
51 cv_.wait_for(l, std::chrono::milliseconds(timeMs_), [this]() {
52 return terminate_; });
53 if (terminate_) {
54 return;
55 }
56
57 if (executor_) {
58 executor_();
59 }
60
61 if (isKill_) {
62 KillProcess();
63 }
64 return;
65 }
66
KillProcess()67 void WatchDog::KillProcess()
68 {
69 raise(SIGKILL);
70 }
71
72 } // namespace Camera
73