سؤال

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.

هل كانت مفيدة؟

المحلول

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;
}

نصائح أخرى

You have to implement a handler for signals that could terminate your program.

void handler_function(int signal) {
  //close db connection
  exit(signal);
}

  // somewhere in init:
{
  sigset_t sigs;
  struct sigaction siga_term;

  sigfillset( &sigs );

  siga_term.sa_handler = handler_funciton();
  siga_term.sa_mask = sigs;
  siga_term.sa_flags = 0;

  sigaction( SIGTERM, &siga_term, NULL );
}

consult how to intercept linux signals ? (in C)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top