c/linux无限循环应用: deallocate memory if kill -9 command is called

标签 c linux memory-management free sigkill

我在 Linux 中开发了一个 C 应用程序,其中包含一个无限循环 while(1)。 有一些指针是动态分配的,在无限循环下很有用,所以释放内存的唯一时间是在 ctrl-z 中断 while(1) 之后, ctrl-ckill -9 apppidkillall 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 -9killall 不会启动处理程序。

有人知道为什么吗?是否有改正建议?

最佳答案

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/

相关文章:

linux - AWK 错误 - grep 处或附近的语法错误

c - 从参数使用 Execvp 到 ls

memory-management - 当我们删除该模块时,内核模块泄漏的内存是否会返回到系统?

C++ 在什么时候使用堆而不是栈才有意义?

memory-management - 适用于无需动态内存分配的开发的语言

C 编程 : From string to array

从两个线程在同一个阻塞套接字上调用 recv()

linux - 在没有 ip 的情况下在网络上查找设备

c - C 中的 WMI 查询?

c - malloc 实现?