Use test_environment().
[nssm.git] / service.cpp
index 294497a..30a75d3 100644 (file)
@@ -449,11 +449,15 @@ int start_service(nssm_service_t *service) {
   flags |= CREATE_UNICODE_ENVIRONMENT;\r
 #endif\r
   if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, service->env, service->dir, &si, &pi)) {\r
+    unsigned long exitcode = 3;\r
     unsigned long error = GetLastError();\r
-    if (error == ERROR_INVALID_PARAMETER && service->env) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service->name, service->exe, NSSM_REG_ENV, 0);\r
+    if (error == ERROR_INVALID_PARAMETER && service->env) {\r
+      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service->name, service->exe, NSSM_REG_ENV, 0);\r
+      if (test_environment(service->env)) exitcode = 4;\r
+    }\r
     else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0);\r
     close_output_handles(&si);\r
-    return stop_service(service, 3, true, true);\r
+    return stop_service(service, exitcode, true, true);\r
   }\r
   service->process_handle = pi.hProcess;\r
   service->pid = pi.dwProcessId;\r
@@ -551,12 +555,14 @@ void CALLBACK end_service(void *arg, unsigned char why) {
   /* Check exit code */\r
   unsigned long exitcode = 0;\r
   TCHAR code[16];\r
-  GetExitCodeProcess(service->process_handle, &exitcode);\r
-  if (exitcode == STILL_ACTIVE || get_process_exit_time(service->process_handle, &service->exit_time)) GetSystemTimeAsFileTime(&service->exit_time);\r
-  CloseHandle(service->process_handle);\r
+  if (service->process_handle) {\r
+    GetExitCodeProcess(service->process_handle, &exitcode);\r
+    if (exitcode == STILL_ACTIVE || get_process_exit_time(service->process_handle, &service->exit_time)) GetSystemTimeAsFileTime(&service->exit_time);\r
+    CloseHandle(service->process_handle);\r
+  }\r
+  else GetSystemTimeAsFileTime(&service->exit_time);\r
 \r
   service->process_handle = 0;\r
-  service->pid = 0;\r
 \r
   /*\r
     Log that the service ended BEFORE logging about killing the process\r
@@ -569,7 +575,8 @@ void CALLBACK end_service(void *arg, unsigned char why) {
 \r
   /* Clean up. */\r
   if (exitcode == STILL_ACTIVE) exitcode = 0;\r
-  kill_process_tree(service, service->pid, exitcode, service->pid);\r
+  if (service->pid) kill_process_tree(service, service->pid, exitcode, service->pid);\r
+  service->pid = 0;\r
 \r
   /*\r
     The why argument is true if our wait timed out or false otherwise.\r