我在 Linux 中开发了一个 C 应用程序,其中包含一个无限循环 while(1)
。
有一些指针是动态分配的,在无限循环下很有用,所以释放内存的唯一时间是在 ctrl-z
中断 while(1)
之后, ctrl-c
,kill -9 apppid
,killall appname
。
所以我的想法是关联新的处理程序,将内存释放给中断事件信号。
void deallocatehandler(int signal){ printf("Memory Deallocation\n"); exit(0);}
int main(){
signal(SIGINT, &deallocatehandler);
signal(SIGTSTP, &deallocatehandler);
signal(SIGKILL, &deallocatehandler);
while(1){
/**
Some code here
**/
}
}
如果我按 ctrl-c 或 ctrl-z,将调用处理程序,但问题出在 SIGKILL。命令 kill -9
和 killall
不会启动处理程序。
有人知道为什么吗?是否有改正建议?
最佳答案
SIGKILL 的全部意义在于无论如何都要终止进程。这就是为什么不允许您处理它。
在大多数情况下,您从 SIGTERM 开始,让进程有机会顺利退出。当 SIGTERM 不起作用时,SIGKILL 通常用作最后的手段。毕竟,SIGTERM 的预期行为是进程退出。如果不是,您就知道出问题了。
来自manual
The SIGTERM signal is a generic signal used to cause program termination. Unlike SIGKILL, this signal can be blocked, handled, and ignored. It is the normal way to politely ask a program to terminate.
...
The SIGKILL signal is used to cause immediate program termination. It cannot be handled or ignored, and is therefore always fatal. It is also not possible to block this signal.
在同一个文档中,你还可以阅读这个有趣的东西
In fact, if SIGKILL fails to terminate a process, that by itself constitutes an operating system bug which you should report.
关于c/linux无限循环应用: deallocate memory if kill -9 command is called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908181/