我必须管理以下信号:SIGHUP
, SIGINT
, SIGQUIT
,SIGTERM
下面的代码是一个示例SIGHUP
:
int sock_ds, acc_sock_ds; //TCP sockets
void shutdown(int sig){
close(sock_ds);
close(acc_sock_ds);
raise(sig);
}
/*Sets the disposition of a signal
* Returns 0 on success, -1 on error */
int sig_disp(int sig, void (* handler)(int), int flag){
struct sigaction sa;
memset((char *)&sa, 0, sizeof(sa));
sa.sa_handler = handler;
sa.sa_flags = flag;
sigemptyset(&sa.sa_mask);
return sigaction(sig, &sa, NULL);
}
int main(){
/*...*/
/*--- Signal management ---*/
sigset_t set;
/*sigset filling with all signal*/
if(sigfillset(&set) == -1){
fprintf(stderr, "Signal set fill error\n");
exit(EXIT_FAILURE);
}
/*...*/
if(sigdelset(&set, SIGHUP) == -1){
fprintf(stderr, "Signal set action error\n");
exit(EXIT_FAILURE);
}
/*...*/
/*Changing signals disposition*/
if(sig_disp(SIGHUP, shutdown, SA_RESETHAND));
/*...*/
/*Remaining signals are inserted into process signal mask (blocked) */
if(sigprocmask(SIG_BLOCK, &set, NULL) == -1){
fprintf(stderr, "Process signal mask action error\n");
exit(EXIT_FAILURE);
}
/*...*/
}
我的想法是重新激活信号的默认处理,即终止进程并在清理操作后重新引发相同的信号。
我如何传递sig
给关机功能sa.sa_handler = handler;
?
此外,在这些情况下,通常会采取哪些清洁措施?我的场景是带有 TCP 套接字和一些打开文件的单线程服务器。