看门狗定时器(Watchdog Timer, WDT)是微控制器(MCU)中一种重要的安全机制,用于检测和恢复系统故障。其主要功能是在系统出现软件故障或程序跑飞时自动复位MCU,使系统恢复正常运行。
Rockchip watchdog 驱动支持Linux下标准的 watchdog框架,可以支持Linux下标准的 watchdog 编程方式。
"/dev/watchdog0"的节点默认属于root用户,需要使用如下命令赋予其他用户组操作权限
su
chmod 666 /dev/watchdog0
开启看门狗并执行一次喂狗,如果开启看门狗后一段时间(默认是40s左右)没有喂狗,则系统重启
echo 1 > /dev/watchdog0
关闭应用层喂狗(内核驱动自动喂狗)
echo V > /dev/watchdog0
看门狗开启之后默认是不能停止的,因此userspace的程序要停止运行时,需要让驱动来喂狗
JAVA代码如下
此代码实现了如下功能,按下START WDT按钮,则启动一个线程,定时(10s)执行喂狗,按下 STOP WDT按钮,关闭看门狗
在 onCreate 添加按键
button8.setText("start wdt");
button8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (wdtThread != null && wdtThread.isAlive()) {
// 停止线程
wdtThread.interrupt();
wdtThread = null;
button8.setText("start wdt");
textDisplay.setText("stop watchdog\n");
try {
writeToFile("/dev/watchdog0","V");
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
// 启动线程
wdtThread = new Thread(new Runnable() {
@Override
public void run() {
feedWatchdog();
}
});
wdtThread.start();
button8.setText("stop wdt");
textDisplay.setText("start watchdog\n");
}
}
});
}
线程实现如下
private void feedWatchdog() {
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(10000);
try {
writeToFile("/dev/watchdog0","1");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} catch (InterruptedException e) {
// 线程被中断,正常退出
}
}
读写函数实现如下
public static void writeToFile(String fileName, String content) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content);
writer.flush();
}
}
public static String readFileToString(String fileName) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
}
return null;
}
此apk中可以正常喂狗和停止看门狗,如果开启了看门狗后app直接退出,则一段时间后会触发系统复位