Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 当程序被用户终止时,如何关闭初始化的连接_C_Sockets_Postgresql_Termination_Libpq - Fatal编程技术网

C 当程序被用户终止时,如何关闭初始化的连接

C 当程序被用户终止时,如何关闭初始化的连接,c,sockets,postgresql,termination,libpq,C,Sockets,Postgresql,Termination,Libpq,我正在用C编写一个守护进程,使用库将数据发布到PostgreSQL数据库。 它的结构如下: init(...) // init function, opens connection while(1){export(...)} // sends commands 当有人终止应用程序时,它会在PostgreSQL server上留下打开的连接。我想避免这种情况。在导出(…)函数中打开和关闭连接不是选项,因为此代码是性能相关框架的一部分。您可以安装一个来捕获应用程序终止,并从该处理程序关闭活动连接:

我正在用C编写一个守护进程,使用库将数据发布到PostgreSQL数据库。 它的结构如下:

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

当有人终止应用程序时,它会在PostgreSQL server上留下打开的连接。我想避免这种情况。在导出(…)函数中打开和关闭连接不是选项,因为此代码是性能相关框架的一部分。

您可以安装一个来捕获应用程序终止,并从该处理程序关闭活动连接:

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

您必须为可能终止程序的信号实现一个处理程序

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

咨询由于不便于携带,不建议使用
信号()。应该避免使用它
sigaction()
是首选解决方案。错误<代码>信号
为ISO-C,
sigaction
为POSIX。因此,
信号
实际上更便于携带。但我同意这是老办法,它比
sigaction
有更少的选择。但也要注意,与大多数实际POSIX系统相比,
信号实际上是使用
sigaction
实现的。我在回答中使用了
signal
,因为OP没有提到它的平台,所以这个例子甚至可以在非POSIX系统上运行。我不应该在提到POSIX函数作为替代时写“…便携…”,你是对的(尽管我添加了“…如果可用…”免责声明,顺便说一句)。无论如何,即使是ISO-C,这也不能确保每个
signal()
实现的行为相似。