6cb03e
diff --git a/contrib/pg_upgrade/server.c b/contrib/pg_upgrade/server.c
6cb03e
index c5ecb84..a519a9e 100644
6cb03e
--- a/contrib/pg_upgrade/server.c
6cb03e
+++ b/contrib/pg_upgrade/server.c
6cb03e
@@ -166,7 +166,6 @@ static void
6cb03e
 stop_postmaster_atexit(void)
6cb03e
 {
6cb03e
 	stop_postmaster(true);
6cb03e
-
6cb03e
 }
6cb03e
 
6cb03e
 
6cb03e
@@ -235,7 +234,23 @@ start_postmaster(ClusterInfo *cluster)
6cb03e
 							  false,
6cb03e
 							  "%s", cmd);
6cb03e
 
6cb03e
-	/* Check to see if we can connect to the server; if not, report it. */
6cb03e
+	/*
6cb03e
+	 * We set this here to make sure atexit() shuts down the server,
6cb03e
+	 * but only if we started the server successfully.  We do it
6cb03e
+	 * before checking for connectivity in case the server started but
6cb03e
+	 * there is a connectivity failure.  If pg_ctl did not return success,
6cb03e
+	 * we will exit below.
6cb03e
+	 */
6cb03e
+	if (pg_ctl_return)
6cb03e
+		os_info.running_cluster = cluster;
6cb03e
+
6cb03e
+	/*
6cb03e
+	 * pg_ctl -w might have failed because the server couldn't be started,
6cb03e
+	 * or there might have been a connection problem in _checking_ if the
6cb03e
+	 * server has started.  Therefore, even if pg_ctl failed, we continue
6cb03e
+	 * and test for connectivity in case we get a connection reason for the
6cb03e
+	 * failure.
6cb03e
+	 */
6cb03e
 	if ((conn = get_db_conn(cluster, "template1")) == NULL ||
6cb03e
 		PQstatus(conn) != CONNECTION_OK)
6cb03e
 	{
6cb03e
@@ -249,12 +264,13 @@ start_postmaster(ClusterInfo *cluster)
6cb03e
 	}
6cb03e
 	PQfinish(conn);
6cb03e
 
6cb03e
-	/* If the connection didn't fail, fail now */
6cb03e
+	/*
6cb03e
+	 * If pg_ctl failed, and the connection didn't fail, fail now.  This
6cb03e
+	 * could happen if the server was already running.
6cb03e
+	 */
6cb03e
 	if (!pg_ctl_return)
6cb03e
 		pg_log(PG_FATAL, "pg_ctl failed to start the %s server, or connection failed\n",
6cb03e
 			   CLUSTER_NAME(cluster));
6cb03e
-
6cb03e
-	os_info.running_cluster = cluster;
6cb03e
 }
6cb03e
 
6cb03e