Skip to content

Instantly share code, notes, and snippets.

@dvarrazzo
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvarrazzo/065f343c95f8ea67cf8f to your computer and use it in GitHub Desktop.
Save dvarrazzo/065f343c95f8ea67cf8f to your computer and use it in GitHub Desktop.
Test what happens to a libpq connection when we close the file

A test to verify psycopg issue #263. Compile with:

$ gcc -I$(pg_config --includedir) -c testclose.c
$ gcc -o testclose testclose.o -L$(pg_config --libdir) -lpq

The output (with PostgreSQL 9.3.5) suggests PQstatus is not good to detect the closed fd.

$ ./testclose 
PQconsumeInput is fine
file closed
PQconsumeInput error: could not receive data from server: Bad file descriptor

PQstatus 0 CONNECTION_OK: 0
PQxnstatus 0 IDLE: 0
#include <stdio.h>
#include <unistd.h>
#include <libpq-fe.h>
int main(int argc, char **argv)
{
PGconn *conn;
char *conninfo = "";
if (argc >= 2) {
conninfo = argv[1];
}
conn = PQconnectdb(conninfo);
if (PQstatus(conn) != CONNECTION_OK) {
printf("bad connection: %s\n", PQerrorMessage(conn));
return 1;
}
if (1 == PQconsumeInput(conn)) {
printf("PQconsumeInput is fine\n");
} else {
printf("PQconsumeInput error: %s\n", PQerrorMessage(conn));
return 1;
}
close(PQsocket(conn));
printf("file closed\n");
if (1 == PQconsumeInput(conn)) {
printf("PQconsumeInput 2 is fine??\n");
} else {
printf("PQconsumeInput error: %s\n", PQerrorMessage(conn));
}
printf("PQstatus %d CONNECTION_OK: %d\n", PQstatus(conn), CONNECTION_OK);
printf("PQxnstatus %d IDLE: %d\n", PQtransactionStatus(conn), PQTRANS_IDLE);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment