1. 程式人生 > 實用技巧 >PostgreSQL資料庫集簇初始化——initdb初始化資料庫(設定中斷訊號處理函式)

PostgreSQL資料庫集簇初始化——initdb初始化資料庫(設定中斷訊號處理函式)

  設定中斷訊號處理函式,對終端命令列SIGHUP、程式中斷SIGINT、程式退出SIGQUIT、軟體中斷SIGTERM和管道中斷SIGPIPE等訊號進行遮蔽,保證初始化工作順利進行。

 1 /* now we are starting to do real work, trap signals so we can clean up */
 2 /* some of these are not valid on Windows */
 3 #ifdef SIGHUP
 4     pqsignal(SIGHUP, trapsig);
 5 #endif
 6 #ifdef SIGINT
 7     pqsignal(SIGINT, trapsig);
8 #endif 9 #ifdef SIGQUIT 10 pqsignal(SIGQUIT, trapsig); 11 #endif 12 #ifdef SIGTERM 13 pqsignal(SIGTERM, trapsig); 14 #endif 15 /* Ignore SIGPIPE when writing to backend, so we can clean up */ 16 #ifdef SIGPIPE 17 pqsignal(SIGPIPE, SIG_IGN); 18 #endif

  trapsig函式訊號處理回撥函式,Windows執行時文件(http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp)禁止訊號處理回撥函式處理,包括IO、memory分配和系統呼叫。如果正在處理SIGPE,僅允許jmpbuf。I avoided doing the forbidden things by setting a flag instead of callingexit_nicely() directly. Windows下的SIGINT的行為:WIN32應用不支援SIGINT,包括Window 98/Me 和Windows NT/2000/XP。當按下CTRL+C時,Win32作業系統產生新的thread來處理中斷。這會造成單thread比如UNIX,成為multithread,導致不正常的行為。I have no idea how to handle this. (Strange they call UNIX an application!)

So this will need some testing on Windows. 該回調函式呼叫後再次設定處理回撥函式,設定caught_signal全域性靜態變數。

1 static void trapsig(int signum){
2     /* handle systems that reset the handler, like Windows (grr) */
3     pqsignal(signum, trapsig);
4     caught_signal = true;
5 }

  pgsignal函式處於src/backend/libpq/pqsignal.c中,下面的程式碼用於處於針對不同的平臺使用不同的訊號設定函式。

 1 #ifndef WIN32
 2 /* Set up a signal handler */
 3 pqsigfunc pqsignal(int signo, pqsigfunc func) {
 4 #if !defined(HAVE_POSIX_SIGNALS)
 5     return signal(signo, func);
 6 #else
 7     struct sigaction act, oact;
 8     act.sa_handler = func;
 9     sigemptyset(&act.sa_mask);
10     act.sa_flags = 0;
11     if (signo != SIGALRM)
12         act.sa_flags |= SA_RESTART;
13 #ifdef SA_NOCLDSTOP
14     if (signo == SIGCHLD)
15         act.sa_flags |= SA_NOCLDSTOP;
16 #endif
17     if (sigaction(signo, &act, &oact) < 0)
18         return SIG_ERR;
19     return oact.sa_handler;
20 #endif   /* !HAVE_POSIX_SIGNALS */
21 }
22 #endif   /* WIN32 */