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