在 C 中捕获 SIGTERM

标签 c signals

我正在努力学习如何捕捉 sigterm 以完成我在类里面的一项更大的作业。我正在执行此 tutorial 中的步骤但是它对我不起作用。当我输入命令“kill [process id]”时, sleep 不会停止,只会继续。我试过杀死 child 和 parent 的 ID,但没有任何反应。有任何想法吗?这是我拥有的:

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

volatile sig_atomic_t done = 0;

void term(int signum)
{
   printf("Caught!\n");
   done = 1;
}

int main(int argc, char *argv[])
{
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = term;
    sigaction(SIGTERM, &action, NULL);

    int pid = getpid();
    int parentID = getppid();
    printf("PID is %d  and Parent is %d \n",pid, parentID);

    int loop = 0;
    while (!done)
    {
        printf("PID is %d  and Parent is %d \n",pid, parentID);
        int t = sleep(10);
        /* sleep returns the number of seconds left if
         * interrupted */
        while (t > 0)
        {
            printf("Loop run was interrupted with %d "
                   "sec to go, finishing...\n", t);
            t = sleep(t);
        }
        printf("Finished loop run %d.\n", loop++);
    }

    printf("done.\n");
    return 0;
}

最佳答案

工作正常:

> cat > sig.c    # paste your code
> gcc sig.c
> ./a.out &
[1] 20549
PID is 20549  and Parent is 15574
PID is 20549  and Parent is 15574
> kill 20549
Caught!
Loop run was interrupted with 1 sec to go, finishing...
> Finished loop run 0.
done.
>
[1]    Done                          ./a.out

关于在 C 中捕获 SIGTERM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33848558/

相关文章:

c - 假设我们有一个非常大的结构在分配时占用巨大的内存空间

c++ - C/C++ : Automatically initialize pointers to null in visual studio

c++ - 在线程中调用时 memcpy 变慢

c - 为什么 SIGINT 被发送到子进程并且什么都不做?

c - c中栈数据结构解释

c - OS X锁屏用纯C?

c - 两个进程之间的顺序信号

c++ - 信号处理(SIGFPE)

c - 使用 printf 作为重入函数 C

signals - 在 LLDB 中发送信号