You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tcp_watchdog.cpp 3.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // tcp_watchdog.cpp
  2. // Copyright (C) 2006 - 2009 MicroNeil Research Corporation
  3. // See tcp_watchdog.hpp for details.
  4. #include "tcp_watchdog.hpp"
  5. const ThreadType TCPWatchdog::Type("TCPWatchdog"); // Thread type.
  6. const ThreadState TCPWatchdog::Watching("Watching"); // State when waiting to fire.
  7. const ThreadState TCPWatchdog::KilledSocket("KilledSocket"); // Killed The Socket.
  8. const ThreadState TCPWatchdog::LiveAndLetBe("LiveAndLetBe"); // Shutdown without incident.
  9. TCPWatchdog::TCPWatchdog(Socket& SocketToWatch, int Milliseconds) : // Construct with
  10. MySocket(SocketToWatch), // a socket to watch,
  11. MyTimeout(Milliseconds), // a time limit,
  12. StillAlive(true) { // and a true alive flag.
  13. run(); // Run the thread.
  14. }
  15. TCPWatchdog::~TCPWatchdog() { // When we go away, we
  16. stop(); // need to stop.
  17. }
  18. void TCPWatchdog::reset() { // We can be reset by
  19. MyTimeout.restart(); // restarting the timeout.
  20. }
  21. void TCPWatchdog::reset(int Milliseconds) { // We can also be reset by
  22. MyTimeout.setDuration(Milliseconds); // setting a new timeout and
  23. MyTimeout.restart(); // starting fresh.
  24. }
  25. void TCPWatchdog::stop() { // If we are stopped then
  26. MyTimeout.restart(); // we restart the timeout for safety,
  27. if(StillAlive) { // IF we're alive when we get here
  28. CurrentThreadState(LiveAndLetBe); // we are "calling off the dog".
  29. }
  30. StillAlive = false; // falsify our alive flag, and
  31. join(); // wait for our thread to end.
  32. }
  33. void TCPWatchdog::myTask() { // This is the job we do.
  34. const int OneSecond = 1000; // One second in milliseconds.
  35. Sleeper WaitATic(OneSecond); // Set up a one second sleeper.
  36. while(StillAlive) { // While we are alive,
  37. CurrentThreadState(Watching); // we are watching the clock.
  38. WaitATic(); // Every second or so we will
  39. if(MyTimeout.isExpired()) { // check to see if we've expired.
  40. CurrentThreadState(KilledSocket); // If the clock expires - we kill!
  41. StillAlive = false; // To do that, we turn ourselves
  42. MySocket.close(); // off and close the socket.
  43. }
  44. }
  45. }