如何在用户终止程序时关闭初始化连接

时间:2013-01-09 16:16:15

标签: c sockets postgresql termination libpq

我在C中编写一个守护进程,使用libpq库将数据发布到PostgreSQL数据库。 它有这样的结构:

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

当某人杀死该应用程序时,它会在PostgreSQL服务器上保持打开连接。我想避免这种情况。导出(...)函数中的打开和关闭连接不是一个选项,因为此代码是性能相关框架的一部分。

2 个答案:

答案 0 :(得分:1)

您可以安装 signal 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;
}

答案 1 :(得分:1)

您必须为可以终止程序的信号实现处理程序。

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

咨询how to intercept linux signals ? (in C)