選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

service.cpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. // \file service.cpp
  2. //
  3. // Copyright (C) 2014 MicroNeil Research Corporation.
  4. //
  5. // This program is part of the MicroNeil Research Open Library Project. For
  6. // more information go to http://www.microneil.com/OpenLibrary/index.html
  7. //
  8. // This program is free software; you can redistribute it and/or modify it
  9. // under the terms of the GNU General Public License as published by the
  10. // Free Software Foundation; either version 2 of the License, or (at your
  11. // option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful, but WITHOUT
  14. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. // more details.
  17. //
  18. // You should have received a copy of the GNU General Public License along with
  19. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  20. // Place, Suite 330, Boston, MA 02111-1307 USA
  21. //==============================================================================
  22. #ifdef WIN32
  23. #include <windows.h>
  24. #include <strsafe.h>
  25. #else
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <fcntl.h>
  30. #include <signal.h>
  31. #endif
  32. #ifdef DEBUG_LOG_FILE
  33. #include <fstream>
  34. #endif
  35. #include <cstdio>
  36. #include <cstdlib>
  37. #include <thread>
  38. #include "service.hpp"
  39. #ifdef WIN32
  40. // Application main entry point for Windows.
  41. int main(int argc, char *argv[]) {
  42. #ifdef DEBUG_LOG_FILE
  43. std::ofstream logStream;
  44. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  45. logStream << "main. argc: " << argc << std::endl;
  46. for (int i = 0; i < argc; i++) {
  47. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  48. }
  49. logStream.close();
  50. #endif
  51. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  52. return service.main(argc, (char **) argv);
  53. }
  54. // Service entry point for Windows.
  55. VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv) {
  56. #ifdef DEBUG_LOG_FILE
  57. std::ofstream logStream;
  58. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  59. logStream << "ServiceMain. argc: " << argc << std::endl;
  60. for (unsigned int i = 0; i < argc; i++) {
  61. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  62. }
  63. logStream.close();
  64. #endif
  65. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  66. return service.serviceMain(argc, argv);
  67. }
  68. /// Control message handler for Windows.
  69. VOID WINAPI ServiceCtrlHandler(DWORD message) {
  70. #ifdef DEBUG_LOG_FILE
  71. std::ofstream logStream;
  72. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  73. logStream << "ServiceCtrlHandler. message: " << message
  74. << ". Calling processCtrlMessage" << std::endl;
  75. logStream.close();
  76. #endif
  77. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  78. service.processCtrlMessage(message);
  79. #ifdef DEBUG_LOG_FILE
  80. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  81. logStream << "ServiceCtrlHandler. Done." << std::endl;
  82. logStream.close();
  83. #endif
  84. }
  85. #else
  86. // Main program for *nix daemon.
  87. int main(int argc, char *argv[]) {
  88. CodeDweller::Service &service = CodeDweller::Service::getInstance();
  89. return service.main(argc, argv);
  90. }
  91. #endif
  92. namespace CodeDweller {
  93. std::mutex Service::objectMutex;
  94. std::vector<std::string> Service::cmdLineArgs;
  95. bool Service::pauseReceived = false;
  96. bool Service::resumeReceived = false;
  97. bool Service::stopReceived = false;
  98. std::vector<Service::Callback *> Service::pauseCallbacks;
  99. std::vector<Service::Callback *> Service::resumeCallbacks;
  100. std::vector<Service::Callback *> Service::stopCallbacks;
  101. int Service::callbackTimeout_ms = 30 * 1000;
  102. Service::Service() {
  103. }
  104. Service &Service::getInstance() {
  105. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  106. static Service service;
  107. return service;
  108. }
  109. int Service::main(int argc, char *argv[]) {
  110. // Under Windows, only arg 0 is passed. Under *nix, all arguments
  111. // are passed.
  112. loadArguments(argc, (char **) argv);
  113. #ifdef DEBUG_LOG_FILE
  114. std::ofstream logStream;
  115. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  116. logStream << "Service::main. argc: " << argc << std::endl;
  117. for (int i = 0; i < argc; i++) {
  118. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  119. }
  120. logStream.close();
  121. #endif
  122. #ifdef WIN32
  123. SERVICE_TABLE_ENTRY ServiceTable[] = {
  124. {(LPTSTR) "", ServiceMain},
  125. {NULL, NULL}
  126. };
  127. if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
  128. return GetLastError();
  129. }
  130. return 0;
  131. #else
  132. pid_t pid;
  133. // Fork the process.
  134. pid = fork();
  135. if (pid < 0) {
  136. perror("Error from first fork");
  137. return(EXIT_FAILURE);
  138. }
  139. // Terminate the parent.
  140. if (pid > 0) {
  141. return(EXIT_SUCCESS);
  142. }
  143. // This is the child. Become the session leader.
  144. if (setsid() < 0) {
  145. perror("Error from setsid");
  146. return(EXIT_FAILURE);
  147. }
  148. // Fork again.
  149. pid = fork();
  150. if (pid < 0) {
  151. perror("Error from second fork");
  152. return(EXIT_FAILURE);
  153. }
  154. // Terminate the parent.
  155. if (pid > 0) {
  156. return(EXIT_SUCCESS);
  157. }
  158. // Set default file permissions. This call always succeeds.
  159. umask(0);
  160. // Disassociate the process from the default directory of the
  161. // grandparent.
  162. if (chdir("/") != 0) {
  163. perror("Error from chdir");
  164. return(EXIT_FAILURE);
  165. }
  166. // Initialize the set of signals to wait for.
  167. if (sigemptyset(&signalSet) != 0) {
  168. perror("Error from sigemptyset");
  169. return(EXIT_FAILURE);
  170. }
  171. if ((sigaddset(&signalSet, SIGTSTP) != 0) ||
  172. (sigaddset(&signalSet, SIGCONT) != 0) ||
  173. (sigaddset(&signalSet, SIGTERM) != 0)) {
  174. perror("Error from sigaddset");
  175. return(EXIT_FAILURE);
  176. }
  177. // Block the signals.
  178. if (sigprocmask(SIG_BLOCK, &signalSet, NULL) != 0) {
  179. perror("Error from sigprocmask");
  180. return(EXIT_FAILURE);
  181. }
  182. // Close all open file descriptors.
  183. for (int fd = 2; fd >= 0; fd--) {
  184. if (close(fd) != 0) {
  185. // There is no controlling terminal to send any message to.
  186. return(EXIT_FAILURE);
  187. }
  188. }
  189. // Connect standard I/O to the null device.
  190. int fd;
  191. // stdin.
  192. fd = open("/dev/null", O_RDONLY);
  193. if (fd < 0) {
  194. return(EXIT_FAILURE);
  195. }
  196. // stdout.
  197. fd = open("/dev/null", O_WRONLY);
  198. if (fd < 0) {
  199. return(EXIT_FAILURE);
  200. }
  201. // stderr.
  202. fd = open("/dev/null", O_WRONLY);
  203. if (fd < 0) {
  204. return(EXIT_FAILURE);
  205. }
  206. // Start the thread to process messages.
  207. std::thread messageThread(&Service::processMessages, this);
  208. // Run the service.
  209. int status;
  210. status = run();
  211. // Send a Stop message so that messageThread exits.
  212. pthread_kill(messageThread.native_handle(), SIGTERM);
  213. messageThread.join();
  214. return(status);
  215. #endif
  216. }
  217. #ifdef WIN32
  218. void Service::serviceMain(DWORD argc, LPTSTR *argv) {
  219. // Arg 0 contains the service name; skip it. The remaining
  220. // arguments contain the command-line arguments, excluding the
  221. // executable name; append them to the object's argument list.
  222. loadArguments(argc - 1, (char **) argv + 1);
  223. // Register the service control handler with the SCM.
  224. serviceStatusHandle =
  225. RegisterServiceCtrlHandler("", ServiceCtrlHandler);
  226. #ifdef DEBUG_LOG_FILE
  227. std::ofstream logStream;
  228. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  229. logStream << "ServiceMain. argc: " << argc << std::endl;
  230. for (DWORD i = 0; i < argc; i++) {
  231. logStream << "arg " << i << ": '" << argv[i] << "'" << std::endl;
  232. }
  233. logStream << " serviceStatusHandle == NULL: " <<
  234. (NULL == serviceStatusHandle) << std::endl;
  235. logStream.close();
  236. #endif
  237. if (serviceStatusHandle == NULL) {
  238. return;
  239. }
  240. ZeroMemory(&serviceStatus, sizeof(serviceStatus));
  241. serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  242. serviceStatus.dwControlsAccepted = 0;
  243. serviceStatus.dwCurrentState = SERVICE_START_PENDING;
  244. serviceStatus.dwWin32ExitCode = NO_ERROR;
  245. serviceStatus.dwServiceSpecificExitCode = 0;
  246. serviceStatus.dwCheckPoint = 0;
  247. serviceStatus.dwWaitHint = 5000;
  248. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  249. // Tell the service controller that the service has started.
  250. serviceStatus.dwControlsAccepted =
  251. SERVICE_ACCEPT_STOP |
  252. SERVICE_ACCEPT_PAUSE_CONTINUE;
  253. serviceStatus.dwCurrentState = SERVICE_RUNNING;
  254. serviceStatus.dwWin32ExitCode = 0;
  255. serviceStatus.dwCheckPoint = 0;
  256. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  257. #ifdef DEBUG_LOG_FILE
  258. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  259. logStream << "Starting application thread." << std::endl;
  260. logStream.close();
  261. #endif
  262. // Start the application thread.
  263. int status;
  264. status = run();
  265. // Change status to stopped.
  266. serviceStatus.dwControlsAccepted = 0;
  267. serviceStatus.dwCurrentState = SERVICE_STOPPED;
  268. serviceStatus.dwWin32ExitCode = status;
  269. serviceStatus.dwCheckPoint = 0;
  270. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  271. #ifdef DEBUG_LOG_FILE
  272. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  273. logStream << "Exiting." << std::endl;
  274. logStream.close();
  275. #endif
  276. return;
  277. }
  278. #endif
  279. void Service::loadArguments(int argc, char *argv[]) {
  280. for (int i = 0; i < argc; i++) {
  281. cmdLineArgs.push_back(argv[i]);
  282. }
  283. }
  284. const std::vector<std::string> &Service::arguments() {
  285. return cmdLineArgs;
  286. }
  287. void Service::setCallbackTimeout_ms(int timeout_ms) {
  288. callbackTimeout_ms = (timeout_ms < 1 ? 1 : timeout_ms);
  289. }
  290. void Service::onPauseCall(Callback &pauseFunctor) {
  291. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  292. pauseCallbacks.push_back(&pauseFunctor);
  293. }
  294. void Service::onResumeCall(Callback &resumeFunctor) {
  295. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  296. resumeCallbacks.push_back(&resumeFunctor);
  297. }
  298. void Service::onStopCall(Callback &stopFunctor) {
  299. std::lock_guard<std::mutex> scopeMutex(objectMutex);
  300. stopCallbacks.push_back(&stopFunctor);
  301. }
  302. bool Service::receivedPause() {
  303. return (pauseReceived);
  304. }
  305. bool Service::receivedResume() {
  306. return (resumeReceived);
  307. }
  308. bool Service::receivedStop() {
  309. return (stopReceived);
  310. }
  311. void Service::clearReceivedPause() {
  312. pauseReceived = false;
  313. }
  314. void Service::clearReceivedResume() {
  315. resumeReceived = false;
  316. }
  317. void Service::clearReceivedStop() {
  318. stopReceived = false;
  319. }
  320. #ifdef WIN32
  321. void Service::processCtrlMessage(DWORD message) {
  322. #ifdef DEBUG_LOG_FILE
  323. std::ofstream logStream;
  324. auto startTime = std::chrono::steady_clock::now();
  325. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  326. logStream << "processCtrlMessage. message: " << message << std::endl;
  327. logStream.close();
  328. #endif
  329. switch (message) {
  330. case SERVICE_CONTROL_PAUSE:
  331. #ifdef DEBUG_LOG_FILE
  332. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  333. logStream << "processCtrlMessage. Received Pause" << std::endl;
  334. logStream.close();
  335. #endif
  336. serviceStatus.dwControlsAccepted = 0;
  337. serviceStatus.dwCurrentState = SERVICE_PAUSE_PENDING;
  338. serviceStatus.dwWin32ExitCode = NO_ERROR;
  339. serviceStatus.dwCheckPoint = 1;
  340. serviceStatus.dwWaitHint = callbackTimeout_ms;
  341. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  342. pauseReceived = true;
  343. #ifdef DEBUG_LOG_FILE
  344. startTime = std::chrono::steady_clock::now();
  345. #endif
  346. for (auto callback : pauseCallbacks) {
  347. (*callback)();
  348. serviceStatus.dwCheckPoint++;
  349. #ifdef DEBUG_LOG_FILE
  350. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  351. logStream << "Service::processCtrlMessage. "
  352. << "Cumulative time after callback (ms): "
  353. << std::chrono::duration_cast<std::chrono::milliseconds>
  354. (std::chrono::steady_clock::now() - startTime).count()
  355. << ", dwWaitHint: " << serviceStatus.dwWaitHint
  356. << std::endl;
  357. logStream.close();
  358. #endif
  359. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  360. #ifdef DEBUG_LOG_FILE
  361. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  362. logStream << "Service::processCtrlMessage. "
  363. << "Cumulative time after SetServiceStatus (ms): "
  364. << std::chrono::duration_cast<std::chrono::milliseconds>
  365. (std::chrono::steady_clock::now() - startTime).count()
  366. << std::endl;
  367. logStream.close();
  368. #endif
  369. }
  370. serviceStatus.dwControlsAccepted =
  371. SERVICE_ACCEPT_SHUTDOWN |
  372. SERVICE_ACCEPT_STOP |
  373. SERVICE_ACCEPT_PAUSE_CONTINUE;
  374. serviceStatus.dwCurrentState = SERVICE_PAUSED;
  375. serviceStatus.dwWin32ExitCode = NO_ERROR;
  376. serviceStatus.dwCheckPoint = 0;
  377. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  378. #ifdef DEBUG_LOG_FILE
  379. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  380. logStream << "Service::processCtrlMessage. "
  381. << "Cumulative time after final SetServiceStatus (ms): "
  382. << std::chrono::duration_cast<std::chrono::milliseconds>
  383. (std::chrono::steady_clock::now() - startTime).count()
  384. << std::endl;
  385. logStream.close();
  386. #endif
  387. break;
  388. case SERVICE_CONTROL_CONTINUE:
  389. #ifdef DEBUG_LOG_FILE
  390. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  391. logStream << "processCtrlMessage. Received Resume" << std::endl;
  392. logStream.close();
  393. #endif
  394. serviceStatus.dwControlsAccepted = 0;
  395. serviceStatus.dwCurrentState = SERVICE_CONTINUE_PENDING;
  396. serviceStatus.dwWin32ExitCode = NO_ERROR;
  397. serviceStatus.dwCheckPoint = 1;
  398. serviceStatus.dwWaitHint = callbackTimeout_ms;
  399. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  400. resumeReceived = true;
  401. for (auto callback : resumeCallbacks) {
  402. (*callback)();
  403. serviceStatus.dwCheckPoint++;
  404. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  405. }
  406. serviceStatus.dwControlsAccepted =
  407. SERVICE_ACCEPT_SHUTDOWN |
  408. SERVICE_ACCEPT_STOP |
  409. SERVICE_ACCEPT_PAUSE_CONTINUE;
  410. serviceStatus.dwCurrentState = SERVICE_RUNNING;
  411. serviceStatus.dwWin32ExitCode = NO_ERROR;
  412. serviceStatus.dwCheckPoint = 0;
  413. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  414. break;
  415. case SERVICE_CONTROL_STOP:
  416. case SERVICE_CONTROL_SHUTDOWN:
  417. #ifdef DEBUG_LOG_FILE
  418. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  419. logStream << "processCtrlMessage. Received "
  420. << (message == SERVICE_CONTROL_STOP ? "STOP" : "SHUTDOWN")
  421. << std::endl;
  422. logStream.close();
  423. #endif
  424. serviceStatus.dwControlsAccepted = 0;
  425. serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
  426. serviceStatus.dwWin32ExitCode = NO_ERROR;
  427. serviceStatus.dwCheckPoint = 1;
  428. serviceStatus.dwWaitHint = callbackTimeout_ms;
  429. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  430. stopReceived = true;
  431. for (auto callback : stopCallbacks) {
  432. (*callback)();
  433. serviceStatus.dwCheckPoint++;
  434. (void) SetServiceStatus(serviceStatusHandle, &serviceStatus);
  435. }
  436. break;
  437. default:
  438. break;
  439. }
  440. }
  441. #else
  442. void Service::processMessages() {
  443. int sigNum;
  444. int status;
  445. while (true) {
  446. // Wait for a signal.
  447. status = sigwait(&signalSet, &sigNum);
  448. if (0 != status) {
  449. perror("Error from sigwait");
  450. // TODO: Implement recovery.
  451. ;
  452. }
  453. // Process the message.
  454. switch (sigNum) {
  455. case SIGTSTP:
  456. {
  457. pauseReceived = true;
  458. callbacksActive = true;
  459. // Get the timeout time.
  460. timeoutTime =
  461. std::chrono::steady_clock::now() +
  462. std::chrono::milliseconds(callbackTimeout_ms);
  463. // Start watchdog thread.
  464. std::thread watchdogThread(&Service::watchdog, this);
  465. #ifdef DEBUG_LOG_FILE
  466. std::ofstream logStream;
  467. auto startTime = std::chrono::steady_clock::now();
  468. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  469. logStream << "Service::processMessages. Calling Pause callbacks--"
  470. << std::endl;
  471. #endif
  472. for (auto callback : pauseCallbacks) {
  473. (*callback)();
  474. timeoutTime =
  475. std::chrono::steady_clock::now() +
  476. std::chrono::milliseconds(callbackTimeout_ms);
  477. #ifdef DEBUG_LOG_FILE
  478. logStream << "Service::processMessages. "
  479. << "Cumulative time after callback (ms): "
  480. << std::chrono::duration_cast<std::chrono::milliseconds>
  481. (std::chrono::steady_clock::now() - startTime).count()
  482. << std::endl;
  483. #endif
  484. }
  485. callbacksActive = false;
  486. #ifdef DEBUG_LOG_FILE
  487. logStream << "Service::processMessages. "
  488. << "Cumulative time after all callback (ms): "
  489. << std::chrono::duration_cast<std::chrono::milliseconds>
  490. (std::chrono::steady_clock::now() - startTime).count()
  491. << std::endl;
  492. #endif
  493. watchdogThread.join();
  494. #ifdef DEBUG_LOG_FILE
  495. logStream << "Service::processMessages. "
  496. <<" Cumulative time after joining watchdog (ms): "
  497. << std::chrono::duration_cast<std::chrono::milliseconds>
  498. (std::chrono::steady_clock::now() - startTime).count()
  499. << std::endl;
  500. logStream.close();
  501. #endif
  502. }
  503. break;
  504. case SIGCONT:
  505. {
  506. resumeReceived = true;
  507. callbacksActive = true;
  508. // Get the timeout time.
  509. timeoutTime =
  510. std::chrono::steady_clock::now() +
  511. std::chrono::milliseconds(callbackTimeout_ms);
  512. // Start watchdog thread.
  513. std::thread watchdogThread(&Service::watchdog, this);
  514. for (auto callback : resumeCallbacks) {
  515. (*callback)();
  516. timeoutTime =
  517. std::chrono::steady_clock::now() +
  518. std::chrono::milliseconds(callbackTimeout_ms);
  519. }
  520. callbacksActive = false;
  521. watchdogThread.join();
  522. }
  523. break;
  524. case SIGTERM:
  525. {
  526. stopReceived = true;
  527. callbacksActive = true;
  528. // Get the timeout time.
  529. timeoutTime =
  530. std::chrono::steady_clock::now() +
  531. std::chrono::milliseconds(callbackTimeout_ms);
  532. // Start watchdog thread.
  533. std::thread watchdogThread(&Service::watchdog, this);
  534. for (auto callback : stopCallbacks) {
  535. (*callback)();
  536. timeoutTime =
  537. std::chrono::steady_clock::now() +
  538. std::chrono::milliseconds(callbackTimeout_ms);
  539. }
  540. callbacksActive = false;
  541. watchdogThread.join();
  542. }
  543. // Exit.
  544. return;
  545. break;
  546. default:
  547. ;
  548. } // switch.
  549. } // while.
  550. }
  551. void Service::watchdog() {
  552. #ifdef DEBUG_LOG_FILE
  553. auto startTime = std::chrono::steady_clock::now();
  554. std::ofstream logStream;
  555. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  556. logStream << "**Service::watchdog. Thread starting." << std::endl;
  557. logStream.close();
  558. #endif
  559. // Sleep and check whether the process should exit.
  560. std::chrono::milliseconds sleepTime(100);
  561. while (std::chrono::steady_clock::now() < timeoutTime) {
  562. std::this_thread::sleep_for(sleepTime);
  563. if (!callbacksActive) {
  564. #ifdef DEBUG_LOG_FILE
  565. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  566. logStream << "**Service::watchdog. Exiting at "
  567. << std::chrono::duration_cast<std::chrono::milliseconds>
  568. (std::chrono::steady_clock::now() - startTime).count()
  569. << " ms after starting"
  570. << std::endl;
  571. logStream.close();
  572. #endif
  573. return;
  574. }
  575. #ifdef DEBUG_LOG_FILE
  576. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  577. logStream << "Service::watchdog. Cumulative time since starting (ms): "
  578. << std::chrono::duration_cast<std::chrono::milliseconds>
  579. (std::chrono::steady_clock::now() - startTime).count()
  580. << std::endl;
  581. logStream.close();
  582. #endif
  583. }
  584. // Timeout expired.
  585. #ifdef DEBUG_LOG_FILE
  586. logStream.open(DEBUG_LOG_FILE, std::fstream::app);
  587. logStream << "**Service::watchdog. Callback timeout expired. "
  588. << "Cumulative time (ms): "
  589. << std::chrono::duration_cast<std::chrono::milliseconds>
  590. (std::chrono::steady_clock::now() - startTime).count()
  591. << std::endl;
  592. logStream.close();
  593. #endif
  594. std::exit(EXIT_FAILURE);
  595. }
  596. #endif
  597. }