0

libpqライブラリを使用して PostgreSQL データベースにデータを投稿する C でデーモンを作成しています。次のような構造になっています。

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

誰かがアプリケーションを強制終了すると、PostgreSQL サーバーで接続が開いたままになります。それは避けたい。このコードはパフォーマンスに依存するフレームワークの一部であるため、export(...) 関数で接続を開いたり閉じたりすることはできません。

4

2 に答える 2

1

シグナルハンドラーをインストールしてアプリケーションの強制終了をキャッチし、そのハンドラーからアクティブな接続を閉じることができます。

#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;
}
于 2013-01-09T16:20:33.093 に答える
1

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)

于 2013-01-09T16:21:32.870 に答える