gpt4 book ai didi

linux - 当 Docker 容器的 PID1 退出时,其他进程会发生什么?

转载 作者:IT老高 更新时间:2023-10-28 12:42:47 26 4
gpt4 key购买 nike

考虑以下,它在后台运行 sleep 60 然后退出:

$ cat run.sh 
sleep 60&
ps
echo Goodbye!!!
$ docker run --rm -v $(pwd)/run.sh:/run.sh ubuntu:16.04 bash /run.sh
PID TTY TIME CMD
1 ? 00:00:00 bash
5 ? 00:00:00 sleep
6 ? 00:00:00 ps
Goodbye!!!

这将启动一个 Docker 容器,其中 bash 作为 PID1。然后它 fork/execs 一个 sleep 进程,然后 bash 退出。当 Docker 容器死掉时,sleep 进程也会莫名其妙地死掉。

我的问题是:sleep 进程被杀死的机制是什么?我尝试在子进程中捕获 SIGTERM ,但这似乎没有被绊倒。我的假设是,在关闭容器正在使用的 cgroup 时,某些东西(Docker 或 Linux 内核)正在发送 SIGKILL,但我在任何地方都找不到任何文档来说明这一点。

编辑我最接近的解释是来自 baseimage-docker 的以下引用:

If your init process is your app, then it'll probably only shut down itself, not all the other processes in the container. The kernel will then forcefully kill those other processes, not giving them a chance to gracefully shut down, potentially resulting in file corruption, stale temporary files, etc. You really want to shut down all your processes gracefully.

所以至少按照这个,隐含的意思是当容器退出时,内核会向所有剩余的进程发送一个SIGKILL。但我仍然想弄清楚它是如何决定这样做的(即,它是 cgroups 的一个特性吗?),理想情况下,一个更权威的来源会很好。

最佳答案

好的,我似乎找到了一些更确凿的证据,证明这实际上是 Linux 内核在终止。在 clone(2) 手册页中,有这个有用的部分:

CLONE_NEWPID (since Linux 2.6.24)

The first process created in a new namespace (i.e., the process created using the CLONE_NEWPID flag) has the PID 1, and is the "init" process for the namespace. Children that are orphaned within the namespace will be reparented to this process rather than init(8). Unlike the traditional init process, the "init" process of a PID namespace can terminate, and if it does, all of the processes in the namespace are terminated.

不幸的是,对于命名空间中的进程究竟是如何终止的,这仍然很模糊,但这可能是因为,与正常的进程退出不同,进程表中没有留下任何条目。不管是什么情况,似乎很清楚:

  • 内核本身正在杀死其他进程
  • 他们不会以任何机会进行清理的方式被杀死,使其(几乎?)与 SIGKILL 相同

关于linux - 当 Docker 容器的 PID1 退出时,其他进程会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39739658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com