34.9. Asynchronous Notification
PostgreSQL offers asynchronous notification via theLISTEN
andNOTIFY
commands. A client session registers its interest in a particular notification channel with theLISTEN
command (and can stop listening with theUNLISTEN
command). All sessions listening on a particular channel will be notified asynchronously when aNOTIFY
command with that channel name is executed by any session. A“payload” string can be passed to communicate additional data to the listeners.
libpq applications submitLISTEN
,UNLISTEN
, andNOTIFY
commands as ordinary SQL commands. The arrival ofNOTIFY
messages can subsequently be detected by callingPQnotifies
.
The functionPQnotifies
returns the next notification from a list of unhandled notification messages received from the server. It returns a null pointer if there are no pending notifications. Once a notification is returned fromPQnotifies
, it is considered handled and will be removed from the list of notifications.
PGnotify *PQnotifies(PGconn *conn);typedef struct pgNotify{ char *relname; /* notification channel name */ int be_pid; /* process ID of notifying server process */ char *extra; /* notification payload string */} PGnotify;
After processing aPGnotify
object returned byPQnotifies
, be sure to free it withPQfreemem
. It is sufficient to free thePGnotify
pointer; therelname
andextra
fields do not represent separate allocations. (The names of these fields are historical; in particular, channel names need not have anything to do with relation names.)
Example 34.2 gives a sample program that illustrates the use of asynchronous notification.
PQnotifies
does not actually read data from the server; it just returns messages previously absorbed by anotherlibpq function. In ancient releases oflibpq, the only way to ensure timely receipt ofNOTIFY
messages was to constantly submit commands, even empty ones, and then checkPQnotifies
after eachPQexec
. While this still works, it is deprecated as a waste of processing power.
A better way to check forNOTIFY
messages when you have no useful commands to execute is to callPQconsumeInput
, then checkPQnotifies
. You can useselect()
to wait for data to arrive from the server, thereby using noCPU power unless there is something to do. (SeePQsocket
to obtain the file descriptor number to use withselect()
.) Note that this will work OK whether you submit commands withPQsendQuery
/PQgetResult
or simply usePQexec
. You should, however, remember to checkPQnotifies
after eachPQgetResult
orPQexec
, to see if any notifications came in during the processing of the command.