#include <stdio.h>
#include <stdlib.h>

#include <libpq-fe.h>

static void
exit_nicely(PGconn *conn)
{
    PQfinish(conn);
    exit(1);
}

int
main(int argc, char **argv)
{
    const char *conninfo;
    PGconn     *conn;
    PGresult   *res;
    int         nFields;
    int         i,
                j;

    /*
     * If the user supplies a parameter on the command line, use it as the
     * conninfo string; otherwise default to setting dbname=postgres and using
     * environment variables or defaults for all other connection parameters.
     */
    if (argc > 1)
        conninfo = argv[1];
    else
        conninfo = "dbname = postgres";

    /* Make a connection to the database */
    conn = PQconnectdb(conninfo);

    /* Check to see that the backend connection was successfully made */
    if (PQstatus(conn) != CONNECTION_OK)
    {
        fprintf(stderr, "%s", PQerrorMessage(conn));
        exit_nicely(conn);
    }

    if (!PQenterPipelineMode(conn))
    {
        fprintf(stderr, "%s", PQerrorMessage(conn));
	exit_nicely(conn);
    }

    printf("Issue pg_terminate_backend for the connection, press Enter when done...\n");
    scanf("%*c");

    if (!PQpipelineSync(conn))
    {
        fprintf(stderr, "%s", PQerrorMessage(conn));
	exit_nicely(conn);
    }


    int loop_iterations_count = 0;
    while (PQstatus(conn) != CONNECTION_BAD) {
	res = PQgetResult(conn);
	if (PQresultStatus(res) == PGRES_PIPELINE_SYNC) {
		PQclear(res);
		break;
	}
	PQclear(res);

	if(++loop_iterations_count > 1000) {
		printf("PQgetResult loop got stuck in busy-loop.\n");
		printf("PQstatus: %i\n", PQstatus(conn));
		printf("PQpipelineStatus: %i\n", PQpipelineStatus(conn));
		exit_nicely(conn);
	}
    }

    /* close the connection to the database and cleanup */
    PQfinish(conn);

    printf("Finishing, unexpectedly\n");

    return 0;
}
