首页 > 解决方案 > Is there any way to figure out that child process was killed with SIGKILL by the kernel when the parent process isn't root

问题描述

I have a situation where there is a nonroot (so i can't read kernel logs) parent process and its child, the child may have been killed with SIGKILL by the kernel for consuming a lot of memory. When it happens the parent process should know that the child was killed because of exceeding the limit of memory (ideally), but i don't even know whether i can to figure out that it was killed by SIGKILL, not to mention about the reason. So i need to understand from side of parent process whether the child was killed with SIGKILL, and if it was why it happened (but this is second issue).

Can someone give me advice? Thank you.

标签: cunixkernelsignalskill-process

解决方案


您需要wait(2)在孩子身上并使用宏WIFSIGNALED来检查它是否被信号终止。

int status = 0;

// wait for child to exit
pid_t child_pid = wait(&status);

if (WIFEXITED(status))
{
    printf("exited with %d\n", WEXITSTATUS(status));
}
else if (WIFSIGNALED(status))
{
    printf("Signaled with %d\n", WTERMSIG(status));
}

如果您有多个子进程,则可以使用循环来等待它们。

WTERMSIG(status)将返回信号编号。要找出信号,您可以检查:

if (WTERMSIG(status) == SIGKILL) {
    ...
} else if (WTERMSIG(status) == SIGTERM) {
    ...
}

没有办法确切地确定谁发出了杀戮(无论是通过 OOM 杀手还是其他东西,例如,可以kill -9 PID从 shell 执行)。可以合理地假设信号不会在系统上不加选择地发送,并且通常是内核本身(OOM 杀手)发送SIGKILL.


推荐阅读