Ensure logging threads exit.
[nssm.git] / io.cpp
diff --git a/io.cpp b/io.cpp
index 0c904be..48611b0 100644 (file)
--- a/io.cpp
+++ b/io.cpp
@@ -428,6 +428,24 @@ void close_output_handles(STARTUPINFO *si) {
   if (si->hStdError) CloseHandle(si->hStdError);\r
 }\r
 \r
+void cleanup_loggers(nssm_service_t *service) {\r
+  unsigned long interval = NSSM_CLEANUP_LOGGERS_DEADLINE;\r
+  HANDLE thread_handle = INVALID_HANDLE_VALUE;\r
+\r
+  close_handle(&service->stdout_thread, &thread_handle);\r
+  /* Close write end of the data pipe so logging thread can finalise read. */\r
+  close_handle(&service->stdout_si);\r
+  /* Await logging thread then close read end. */\r
+  if (thread_handle != INVALID_HANDLE_VALUE) WaitForSingleObject(thread_handle, interval);\r
+  close_handle(&service->stdout_pipe);\r
+\r
+  thread_handle = INVALID_HANDLE_VALUE;\r
+  close_handle(&service->stderr_thread, &thread_handle);\r
+  close_handle(&service->stderr_si);\r
+  if (thread_handle != INVALID_HANDLE_VALUE) WaitForSingleObject(thread_handle, interval);\r
+  close_handle(&service->stderr_pipe);\r
+}\r
+\r
 /*\r
   Try multiple times to read from a file.\r
   Returns:  0 on success.\r