[英]'kill -9 process ID' signal handler
我開發了一個程序,該程序使用http服務器中的tcp套接字與客戶端進行通信。 我使用以下代碼創建http服務器:
void http_server_init(void)
{
struct sockaddr_in server;
int cr_port;
for(;;) {
cr_port = conf.port;
int i = (DEFAULT_PORT == cr_port)? 1 : 0;
//Create socket
cr_socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (cr_socket_desc == -1)
{
LOG (ERROR,"Could not open server socket, Error no is : %d, Error description is : %s", errno, strerror(errno));
sleep(1);
continue;
}
/* enable SO_REUSEADDR */
int reusaddr = 1;
if (setsockopt(cr_socket_desc, SOL_SOCKET, SO_REUSEADDR, &reusaddr, sizeof(int)) < 0) {
LOG (WARNING,"setsockopt(SO_REUSEADDR) failed");
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
for(;;i++) {
server.sin_port = htons(cr_port);
//Bind
if( bind(cr_socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
LOG (ERROR,"Could not bind server socket on the port %d, Error no is : %d, Error description is : %s", cr_port, errno, strerror(errno));
cr_port = DEFAULT_PORT + i;
LOG (INFO,"Trying to use another port: %d", cr_port);
continue;
}
break;
}
break;
}
LOG (INFO,"server initiated with the port: %d", cr_port);
}
然后,如果程序退出,我將關閉套接字。
如果程序正常停止(/etc/init.d/myprog stop)
則使用套接字關閉功能
close(cr_socket_desc);
但是,當使用kill -9 PID of my program
終止程序時,我使用以下代碼:
void signal_handler(int signal_num)
{
close(cr_socket_desc);
_exit;
}
void main()
{
....
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = signal_handler;
sigaction(SIGINT, &act, 0);
sigaction(SIGTERM, &act, 0);
sigaction(SIGKILL, &act, 0);
sigaction(SIGSTOP, &act, 0);
......
}
但是該套接字未關閉,因為它已被另一個服務占用。
問題是如何處理kill -9
信號並如何捕獲?
Kill -9發送一個SIGKILL,您無法捕獲或忽略。 (請參閱http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html )。
您也不能使用sigprocmask()阻止SIGKILL。 這樣做的任何嘗試都將被忽略。
您無法捕獲這些SIGKILL的事實意味着,當收到SIGKILL時,您的程序將根本沒有機會運行任何代碼。 SIGKILL是操作系統以極端偏見殺死您的進程的一種方式。
您沒有說為什么要使用kill -9殺死進程。 如果那是您自己執行的操作,則應嘗試發送其他信號(SIGTERM會很好,這是kill默認情況下發送的信號,而沒有任何參數指定其他信號號)。 這將調用您的信號處理程序,並允許您干凈地關閉套接字。
如果您的程序確實卡住了,並且確實需要使用kill -9來擺脫它,則根本無法執行任何干凈的關閉。
您不能捕捉或忽略這些信號,
SIGKILL和SIGSTOP
因此,您可以使用sigprocmask()
阻止該信號。
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.