- (djm) Fix SSH2 not terminating until all background tasks done problem.
diff --git a/ChangeLog b/ChangeLog
index 1467f93..8aaa68f 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,6 @@
+20000929
+ - (djm) Fix SSH2 not terminating until all background tasks done problem.
+
 20000926
  - (djm) Update X11-askpass to 1.0.2 in RPM spec file
  - (djm) Define _REENTRANT to pickup strtok_r() on HP/UX
diff --git a/serverloop.c b/serverloop.c
index be9edfa..50e89ae 100644
--- a/serverloop.c
+++ b/serverloop.c
@@ -110,7 +110,6 @@
 	int save_errno = errno;
 	debug("Received SIGCHLD.");
 	child_terminated = 1;
-	child_has_selected = 0;
 	errno = save_errno;
 }
 
@@ -675,10 +674,10 @@
 				session_close_by_pid(pid, status);
 			child_terminated = 0;
 			signal(SIGCHLD, sigchld_handler2);
+			if (used_sessions() == 0)
+				break;
 		}
 		channel_after_select(&readset, &writeset);
-		if (child_terminated && child_has_selected)
-			break;
 		process_input(&readset);
 		process_output(&writeset);
 	}
diff --git a/session.c b/session.c
index 296dfad..ca12a4f 100644
--- a/session.c
+++ b/session.c
@@ -150,6 +150,8 @@
 /* data */
 #define MAX_SESSIONS 10
 Session	sessions[MAX_SESSIONS];
+static int num_used_sessions;
+
 #ifdef WITH_AIXAUTHENTICATE
 /* AIX's lastlogin message, set in auth1.c */
 char *aixloginmsg;
@@ -1422,6 +1424,7 @@
 			sessions[i].used = 0;
 			sessions[i].self = i;
 		}
+		num_used_sessions = 0;
 		did_init = 1;
 	}
 	for(i = 0; i < MAX_SESSIONS; i++) {
@@ -1440,7 +1443,8 @@
 			s->auth_proto = NULL;
 			s->used = 1;
 			s->pw = NULL;
-			debug("session_new: session %d", i);
+			num_used_sessions++;
+			debug("session_new: session %d (%d used)", i, num_used_sessions);
 			return s;
 		}
 	}
@@ -1853,6 +1857,7 @@
 	session_pty_cleanup(s);
 	session_free(s);
 	session_proctitle(s);
+	num_used_sessions--;
 }
 
 void
@@ -1898,6 +1903,11 @@
 	}
 }
 
+int used_sessions(void)
+{
+	return(num_used_sessions);
+}
+
 char *
 session_tty_list(void)
 {
diff --git a/session.h b/session.h
index bce99f7..69d3b7d 100644
--- a/session.h
+++ b/session.h
@@ -33,5 +33,6 @@
 void	session_input_channel_req(int id, void *arg);
 void	session_close_by_pid(pid_t pid, int status);
 void	session_close_by_channel(int id, void *arg);
+int	used_sessions(void);
 
 #endif