以下是一个简单的 C++ 实现软件看门狗的示例代码: ```cpp #include <iostream> #include <thread> #include <atomic> #include <chrono> // 看门狗超时时间(以毫秒为单位) const int watchdogTimeout = 5000; // 标志,表示程序是否正常运行 std::atomic<bool> isProgramRunning(true); void watchdog() { // 启动一个线程来监控程序状态 std::thread([&]() { while (true) { // 等待一段时间 std::this_thread::sleep_for(std::chrono::milliseconds(watchdogTimeout)); // 如果程序没有在运行,输出错误信息并退出程序 if (!isProgramRunning) { std::cout << "程序出现异常,看门狗触发!" << std::endl; exit(1); } } }).detach(); } int main() { watchdog(); // 模拟程序正常运行 while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); isProgramRunning = true; } return 0; } ``` 额外需要注意的逻辑点: 1. 确保 `watchdogTimeout` 的值设置合理,既不能太短导致误判,也不能太长影响故障检测的及时性。 2. 处理好多线程同步问题,特别是对 `isProgramRunning` 标志的访问。 3. 考虑在程序出现异常时,是否需要进行一些额外的清理操作。 [2024-12-04 10:05:07 | AI写代码神器 | 357点数解答]