编写看门狗程序的方法有多种,下面分别介绍几种常见的方法:
方法一:使用Python的Watchdog库
Python的Watchdog库是一个简单易用的库,用于监控文件系统事件。以下是一个简单的示例,展示如何使用Watchdog监控文件的变化:
```python
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
print(f"呜汪!发现新文件: {event.src_path}")
def on_modified(self, event):
if not event.is_directory:
print(f"汪汪!文件被修改了: {event.src_path}")
def on_deleted(self, event):
if not event.is_directory:
print(f"呜呜!文件被删除了: {event.src_path}")
创建观察者和事件处理器
observer = Observer()
handler = MyHandler()
observer.schedule(handler, path='.', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
```
方法二:使用C++编写守护程序
```cpp
include include include include include void childProcessFunc() { int i = 0; while (true) { ++i; std::cout << "i: "<< i << ", pid: " << getpid() << ", ppid: " << getppid() << std::endl; if (i == 10) { // 子进程主动结束 exit(0); } sleep(1); } } void forkChildProcess(int argc, char *argv[]) { pid_t pid = fork(); if (pid < 0) { std::cerr << "无法创建子进程" << std::endl; return; } if (pid == 0) { // 子进程 childProcessFunc(); } else { // 父进程 int status; waitpid(pid, &status, 0); } } int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv<< " return 1; } std::string filePath = argv; forkChildProcess(argc, argv); return 0; } ``` 方法三:使用Shell脚本 ```bash !/bin/bash 监控的进程名称 process_name="your_process_name" 监控的进程路径 process_path="/path/to/your/program" 无限循环监控进程 while true; do 检查进程是否在运行 if pgrep -x "$process_name" > /dev/null; then echo "$process_name is running." else echo "$process_name is not running. Restarting..." 尝试重新启动进程 "$process_path" fi sleep 5 done ``` 方法四:使用单片机C语言编写看门狗程序