我正在检查与 shell 进程关联的命名空间,如下所示:
# ll /proc/$$/ns
total 0
dr-x--x--x 2 root root 0 May 2 15:10 ./
dr-xr-xr-x 9 root root 0 May 1 18:39 ../
lrwxrwxrwx 1 root root 0 May 2 15:11 cgroup -> cgroup:[4026531835]
lrwxrwxrwx 1 root root 0 May 2 15:11 ipc -> ipc:[4026531839]
lrwxrwxrwx 1 root root 0 May 2 15:11 mnt -> mnt:[4026531840]
lrwxrwxrwx 1 root root 0 May 2 15:11 net -> net:[4026531957]
lrwxrwxrwx 1 root root 0 May 2 15:11 pid -> pid:[4026531836]
lrwxrwxrwx 1 root root 0 May 2 15:11 user -> user:[4026531837]
lrwxrwxrwx 1 root root 0 May 2 15:11 uts -> uts:[4026531838]
据我了解,这些条目指示进程与哪些名称空间关联。我想问一下,标识每个命名空间的数字是从哪里来的?
例如,上面的输出表明进程挂载命名空间是mnt:[4026531840]
。我检查了挂载命名空间结构:
8 struct mnt_namespace {
9 atomic_t count;
10 struct ns_common ns;
11 struct mount * root;
12 struct list_head list;
13 struct user_namespace *user_ns;
14 struct ucounts *ucounts;
15 u64 seq; /* Sequence number to prevent loops */
16 wait_queue_head_t poll;
17 u64 event;
18 unsigned int mounts; /* # of mounts in the namespace */
19 unsigned int pending_mounts;
20 } __randomize_layout;
我没有看到用作条目中使用的标识符的字段/proc/PID/ns/
。那么这些标识符是如何生成的呢?
答案1
它们是文件系统实现的文件的索引节点号nsfs
,可以打开并使用它们setns(2)
将进程与命名空间关联起来。
你可以看看fs/nsfs.c
:
int ns_get_name(char *buf, size_t size, struct task_struct *task,
const struct proc_ns_operations *ns_ops)
{
struct ns_common *ns;
int res = -ENOENT;
const char *name;
ns = ns_ops->get(task);
if (ns) {
name = ns_ops->real_ns_name ? : ns_ops->name;
res = snprintf(buf, size, "%s:[%u]", name, ns->inum);
static int proc_ns_readlink(struct dentry *dentry, char __user *buffer, int bufl
en)
{
...
if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS)) {
res = ns_get_name(name, sizeof(name), task, ns_ops);