We will create an application that will define the Watchdog class and provide an example of its usage. Follow these steps:
- In your working directory, that is, ~/test, create a subdirectory called watchdog.
- Use your favorite text editor to create a file called watchdog.cpp in the watchdog subdirectory.
- Put the required includes in the watchdog.cpp file:
#include <chrono>
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std::chrono_literals;
- Next, we define the Watchdog class itself:
class Watchdog {
std::chrono::seconds seconds;
public:
Watchdog(std::chrono::seconds seconds):
seconds(seconds) {
feed();
}
~Watchdog() {
alarm(0);
}
void feed() {
alarm(seconds.count());
}
};
- Add the main function, which serves as a usage example for our watchdog:
int main() {
Watchdog watchdog(2s);
std::chrono::milliseconds delay = 700ms;
for (int i = 0; i < 10; i++) {
watchdog.feed();
std::cout << delay.count() << "ms delay" << std::endl;
std::this_thread::sleep_for(delay);
delay += 300ms;
}
}
- Add a CMakeLists.txt file containing the build rules for our program:
cmake_minimum_required(VERSION 3.5.1)
project(watchdog)
add_executable(watchdog watchdog.cpp)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
SET(CMAKE_CXX_FLAGS "--std=c++14")
set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabi-g++)
- You can now build and run the application.