Search code examples
csocketspostgresqlterminationlibpq

How to close initialized connections when program is terminated by user


Im writing a daemon in C that posts data to PostgreSQL database using libpq library. It has structure like this:

init(...) // init function, opens connection
while(1){export(...)} // sends commands

When someone kills the application, it leaves open connection on PostgreSQL server. I want to avoid that. Opening and closing connection in export(...) function is not an option, because this code is part of performance dependent framework.


Solution

  • You may install a signal handler to catch the application kill, and close the active connections from that handler:

    #include "signal.h"
    #include "stdio.h"
    #include "stdlib.h"
    
    void catch_sigint( int sig )
    {
        /* Close connections */
    
        /*
         * The software won't exit as you caught SIGINT
         * so explicitly close the process when you're done
         */
        exit( EXIT_SUCCESS );
    }
    
    int main( void )
    {
        /* Catches SIGINT (ctrl-c, for instance) */
        if( signal( SIGINT, catch_sigint ) == SIG_ERR )
        {
            /* Failed to install the signal handler */
            return EXIT_FAILURE;
        }
    
        /* Perform your operations */
        while( 1 );
    
        return EXIT_SUCCESS;
    }