Android WatchDog

本文介绍了Android系统中一个名为`Watchdog`的C++实现,它是一个资源管理工具,用于确保代码块在预设时间内执行完毕。如果超时,`Watchdog`会触发进程崩溃,发送SIGABRT信号。通过创建和销毁定时器,`Watchdog`在进入和退出代码块时进行监控,为关键操作提供时间限制保障。

一. Native C++ watchdog:

代码:

        frameworks/av/media/libwatchdog/include/watchdog/Watchdog.h
        frameworks/av/media/libwatchdog/Watchdog.cpp

 Watchdog.h:

/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ANDROID_WATCHDOG_H
#define ANDROID_WATCHDOG_H

#include <chrono>
#include <time.h>

namespace android {

/*
 * An RAII-style object, which would crash the process if a timeout expires
 * before the object is destroyed.
 * The calling thread would be sent a SIGABORT, which would typically result in
 * a stack trace.
 *
 * Sample usage:
 * {
 *     Watchdog watchdog(std::chrono::milliseconds(10));
 *     DoSomething();
 * }
 * // If we got here, the function completed in time.
 */
class Watchdog final {
public:
    Watchdog(std::chrono::steady_clock::duration timeout);
    ~Watchdog();

private:
    timer_t mTimerId;
};

}  // namespace android

#endif  // ANDROID_WATCHDOG_H

 Watchdog.cpp:

/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "Watchdog"

#include <watchdog/Watchdog.h>

#include <android-base/logging.h>
#include <android-base/threads.h>
#include <signal.h>
#include <time.h>
#include <cstring>
#include <utils/Log.h>

namespace android {

Watchdog::Watchdog(::std::chrono::steady_clock::duration timeout) {
    // Create the timer.
    struct sigevent sev;
    sev.sigev_notify = SIGEV_THREAD_ID;
    sev.sigev_notify_thread_id = base::GetThreadId();
    sev.sigev_signo = SIGABRT;
    sev.sigev_value.sival_ptr = &mTimerId;
    int err = timer_create(CLOCK_MONOTONIC, &sev, &mTimerId);
    if (err != 0) {
        PLOG(FATAL) << "Failed to create timer";
    }

    // Start the timer.
    struct itimerspec spec;
    memset(&spec, 0, sizeof(spec));
    auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(timeout);
    LOG_ALWAYS_FATAL_IF(timeout.count() <= 0, "Duration must be positive");
    spec.it_value.tv_sec = ns.count() / 1000000000;
    spec.it_value.tv_nsec = ns.count() % 1000000000;
    err = timer_settime(mTimerId, 0, &spec, nullptr);
    if (err != 0) {
        PLOG(FATAL) << "Failed to start timer";
    }
}

Watchdog::~Watchdog() {
    // Delete the timer.
    int err = timer_delete(mTimerId);
    if (err != 0) {
        PLOG(FATAL) << "Failed to delete timer";
    }
}

}  // namespace android

 使用:发送的signal可以根据自己的需要来修改

#include <time.h>
#include "Watchdog.h"


int main(int argc, char** argv)
{
    // Watchdog在下面的代码块有效,
    // 如果在5s内,没有出代码块,就会狗叫,定时器就会给自己发送SIGABRT信号。
    // 如果在5s内出下面的代码块,就会调用Watchdog析构函数,timer_delete删除定时器。
    // 要旨:主要针对代码块,出代码块会析构
    {
        android::Watchdog watchdog(std::chrono::seconds(5));
        // 具体工作XXX
        sleep(6);
    }
    return 0;
}

### Android Watchdog 实现与机制 #### 定义与功能 AndroidWatchdog 是一种用于监控系统健康状态的重要组件。其主要职责是在检测到系统无响应或其他异常情况时触发重启操作,从而提高设备稳定性和用户体验[^1]。 #### 工作流程 当调用 `Watchdog.getInstance().start()` 方法时,会创建名为 "watchdog" 的线程并执行其中的 `run()` 函数。此函数分为两个主要部分: - **第一阶段**:定期检查各种关键服务的状态,如 ActivityManagerService (AMS),WindowManagerService (WMS) 等核心进程是否正常运行。 - **第二阶段**:如果发现任何被监视的服务出现问题,则尝试通过发送 ANR(Application Not Responding) 警告给用户,并最终强制重启整个系统来恢复正常的运作环境。 #### 关键类结构 为了更好地理解其实现细节,下面列出了几个重要的 Java 类及其作用: - **`android.os.Watchdog`**: 主要入口点,负责初始化以及管理所有子模块的工作周期。 - **`com.android.server.am.ActivityManagerService` 和其他 Service Classes**: 提供具体业务逻辑处理接口,在这里实现了各自特有的心跳监测算法。 ```java // 示例代码片段展示了一个简化版的心跳检测逻辑 public class CustomHeartbeatMonitor extends Thread { private final Object mLock = new Object(); public void run() { while (!Thread.currentThread().isInterrupted()) { synchronized(mLock){ try{ // 执行实际的健康状况评估工作... sleep(HEARTBEAT_INTERVAL); }catch(Exception e){ Log.e(TAG,"Error during heartbeat check",e); } } } } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kevin@1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值