c - 杀死 -SIGTERM 和 KILLSIG : Safely terminating applications

标签 c linux

在 Linux 系统上,信号 -KILLTERM 发送允许应用程序安全关闭的信号。这些问题可能有点理论性,但我想了解它们。

  1. 当系统发送终止信号时,它发送到哪里?

  2. 是什么让进程或应用程序有时间“安全”终止?

  3. 是否有子进程或类似的东西在查找此信号的应用程序后台运行?

这些问题源于linux watchdog,在看man page的时候看到watchdog的进程是先给给定的PID发送terminate信号,然后是KILL -9信号强制执行。我希望能够利用看门狗内置的安全功能。

最佳答案

查看这段代码,

#include<stdio.h>
#include<signal.h>
#include<stdlib.h>

void cleanUp(){ // Do whatever you want here
    printf("Safely terminating \n");
}

void hand(int sig){ // called when you are sent SIGTERM
    /*
    Here you can safely terminate..
    */
    atexit(cleanUp); // call cleanUp at exit.
    exit(0);
}

int main(){
    signal(SIGTERM, hand); //Assign function to be called on SIGTERM
    /*
    Your code goes here.
    I have put an infinite loop for demonstration.
    */
    printf("Started execution..\n");
    for(;;);
}

这显示了当信号传递到您的应用程序时如何分配函数以供调用。

传递信号SIGTERM对此代码,执行此操作,

kill -SIGTERM <pid>

在这里,<pid> id 您正在运行的程序的进程 ID。

关于c - 杀死 -SIGTERM 和 KILLSIG : Safely terminating applications,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502525/

相关文章:

c - 查找二叉树中最短根到叶路径的总和

C - 使用 for 循环输入二维数组的值会产生与输入的值不同的值

c - 结构指针 - 使用指针访问结构数组

linux - 在设置位置参数时使用 - 和 -- 作为要设置的选项之间的区别

c - 改变 C 指针的值后释放它

c - 相对于标准代码测试 simd 加速的正确方法是什么

linux - 如何在Linux命令行的find命令中使用-regex

c - Linux - 为什么自定义系统调用不能正常使用负数?

linux - TCL、Linux 和 FLOCK

linux - 从以 root 身份运行的 bash 脚本向用户添加 ssh key