Asynchronous Notification

Red Hat Database supports asynchronous notification via the LISTEN and NOTIFY commands. A backend registers its interest in a particular notification condition with the LISTEN command and can stop listening with the UNLISTEN command. All backends listening on a particular condition will be notified asynchronously when a NOTIFY of that condition name is executed by any backend. No additional information is passed from the notifier to the listener. Thus, any actual data that needs to be communicated is transferred through a database relation. Commonly the condition name is the same as the associated relation. Note that it is not necessary to have an associated relation for using asynchronous notifications.

libpq applications submit LISTEN and UNLISTEN commands as ordinary SQL queries. Subsequently, arrival of NOTIFY messages can be detected by calling PQnotifies.

Asynchronous Notification Functions

PQnotifies

PQnotifies returns the next notification from a list of unhandled notification messages received from the backend. Returns NULL if there are no pending notifications. Once a notification is returned from PQnotifies, it is considered handled and will be removed from the list of notifications.
PGnotify* PQnotifies(PGconn *conn);

typedef struct pgNotify { 
    char relname[NAMEDATALEN];   
    int be_pid;
} PGnotify;
where char relname[NAMEDATALEN] is the name of a relation containing data and int be_pid is the process id of the notifying backend. After processing a PGnotify object returned by PQnotifies, be sure to free it with free to avoid a memory leak.

Note

Note that the be_pid is the notifying backend's, not your own backend's PID.

The second sample program (Example 1-2) gives an example of the use of asynchronous notification.

PQnotifies does not actually read backend data; it just returns messages previously absorbed by another libpq function. One way to ensure timely receipt of NOTIFY messages is to constantly submit queries, even empty ones, and then check PQnotifies after each PQexec. While this works, it uses the CPU inefficiently.

The recommended way to check for NOTIFY messages when you have no useful queries to make is to call PQconsumeInput, then check PQnotifies. You can use select(2) to wait for backend data to arrive, thereby wasting no CPU. (See PQsocket for information on how to obtain the file descriptor number to use with select.) Note that this will work whether you submit queries with PQsendQuery/PQgetResult, or simply by using PQexec. You should, however, remember to check PQnotifies after each PQgetResult or PQexec, to see if any notifications arrived during the processing of the query.