I am trying to establish a non-blocking connection to a PostgreSQL database using the libpq library in C, and I want to be able to trigger a notification or callback function once the connection is established.
I know that PQconnectStart() can be used to initiate a non-blocking connection and that PQconnectPoll() can be used to check the status of the connection, but I’m not sure how to trigger a notification or callback function once the connection is established.
PGconn *conn;
PGconnStatusType status;
conn = PQconnectStart("dbname=mydatabase user=myusername password=mypassword");
if (conn == NULL) {
fprintf(stderr, "Connection initialization failedn");
exit(1);
}
while ((status = PQconnectPoll(conn)) != CONNECTION_OK) {
if (status == PGRES_POLLING_FAILED) {
fprintf(stderr, "Connection failed: %sn", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
}
// Connection is established, how do I trigger a notification or callback function?
// Do something with the connection here...
PQfinish(conn);
2
Answers
I don’t think you can do that. You’ll have to call
select()
on the socket. You can start a thread or parallel process that waits withselect()
, the calls your callback.I think that you can use the Notice Receiver.
You can use PQsetNoticeReceiver to set a custom notice receiver callback function that will be called whenever a notice or warning message is received. This callback function can be used to handle and process the received messages according to your application’s requirements.
Documentation Notice Processing