我研究了这个主题,在 Github 上找到了以下代码,上面写着:
// HasNamespace determines if a container is using a particular namespace or the
// host namespace.
// The device number of an unnamespaced /proc/1/ns/{ns} is 4 and anything else is
// higher.
// Only works from inside a container.
Run Code Online (Sandbox Code Playgroud)
但是,该评论已过时,这可以通过以下方式证明:
$ docker run -ti --rm --pid host debian
root@e29ab2d7176b:/# stat --format="%d" /proc/self/ns/net
58
root@e29ab2d7176b:/# stat --format="%d" /proc/self/ns/pid
58
Run Code Online (Sandbox Code Playgroud)
stat --format="%d" /proc/self/ns/pid如果该评论是正确的,则此处应为 4。
进程如何检测它是否在子命名空间中?
最近我开始systemd-nspawn在我的 Arch 盒子上设置其他操作系统实例。我想做的一件事是检测我是否在容器内,如果是,则将发行版名称 (from lsb_release) 添加到终端标题。在基于Debian的系统上,默认.bashrc采用debian_chroot了类似的目的。如何检测我是否在 nspawn 容器内运行?
我假设nsenter,它作为 的子进程运行bash,利用setns系统调用加入现有的命名空间,然后使用exec.
但是,如果在'ing之前nsenter已经调用了,为什么还需要系统调用来确保子进程也将在输入的命名空间中?setnsexecfork
setns(2)
The setns(2) system call allows the calling process to join an
existing namespace. The namespace to join is specified via a
file descriptor that refers to one of the /proc/[pid]/ns files
described below.
Run Code Online (Sandbox Code Playgroud)
...
-F, --no-fork
Do not fork before exec'ing the specified program. By
default, when entering a PID namespace, nsenter calls fork
before calling exec …Run Code Online (Sandbox Code Playgroud) 我有几个容器(systemd-nspawn基于),我想知道我是应该设置时间(通过systemd-timesyncd)还是由主机维护?