--- a/hostapd/main.c
+++ b/hostapd/main.c
@@ -32,6 +32,8 @@
 extern int wpa_debug_level;
 extern int wpa_debug_show_keys;
 extern int wpa_debug_timestamp;
+static int daemonize = 0;
+static char *pid_file = NULL;
 
 extern struct wpa_driver_ops *wpa_drivers[];
 
@@ -146,6 +148,14 @@ static void hostapd_logger_cb(void *ctx,
 }
 #endif /* CONFIG_NO_HOSTAPD_LOGGER */
 
+static void hostapd_setup_complete_cb(void *ctx)
+{
+	if (daemonize && os_daemonize(pid_file)) {
+		perror("daemon");
+		return;
+	}
+	daemonize = 0;
+}
 
 /**
  * hostapd_init - Allocate and initialize per-interface data
@@ -189,6 +199,7 @@ static struct hostapd_iface * hostapd_in
 		if (hapd == NULL)
 			goto fail;
 		hapd->msg_ctx = hapd;
+		hapd->setup_complete_cb = hostapd_setup_complete_cb;
 	}
 
 	return hapd_iface;
@@ -425,8 +436,6 @@ static void hostapd_global_deinit(const 
 #endif /* CONFIG_NATIVE_WINDOWS */
 
 	eap_server_unregister_methods();
-
-	os_daemonize_terminate(pid_file);
 }
 
 
@@ -452,11 +461,6 @@ static int hostapd_global_run(struct hap
 	}
 #endif /* EAP_SERVER_TNC */
 
-	if (daemonize && os_daemonize(pid_file)) {
-		perror("daemon");
-		return -1;
-	}
-
 	eloop_run();
 
 	return 0;
@@ -540,8 +544,7 @@ int main(int argc, char *argv[])
 	struct hapd_interfaces interfaces;
 	int ret = 1;
 	size_t i;
-	int c, debug = 0, daemonize = 0;
-	char *pid_file = NULL;
+	int c, debug = 0;
 	const char *log_file = NULL;
 	const char *entropy_file = NULL;
 
