【问题标题】:Why I couldn't use mount --bind /proc/<pid>/ns/mnt to another file in ubuntu?为什么我不能使用 mount --bind /proc/<pid>/ns/mnt 到 ubuntu 中的另一个文件?
【发布时间】:2016-01-14 06:56:01
【问题描述】:

最近,我正在学习 linux 命名空间。 我希望即使进程结束,我仍然可以附加该进程所在的命名空间。 有人告诉我可以使用mount --bind /proc/&lt;pid&gt;/ns/pid ./pid 来保持这个文件打开。所以我试了一下。 挂载uts的时候,user、ipc、pid、net……都还好……

root@ubuntu:/home/jiashenh/workspace# touch uts
root@ubuntu:/home/jiashenh/workspace# mount --bind /proc/171/ns/uts ./uts

但是说到mnt……我也是这样用的……

root@ubuntu:/home/jiashenh/workspace# touch mnt    
root@ubuntu:/home/jiashenh/workspace# mount --bind /proc/171/ns/mnt ./mnt
mount: wrong fs type, bad option, bad superblock on /proc/171/ns/mnt,
       missing codepage or helper program, or other error

       In some cases useful info is found in syslog - try
       dmesg | tail or so

它失败了.....那么谁能告诉我如何解决它? .

【问题讨论】:

    标签: linux mount


    【解决方案1】:

    如果在同一个挂载命名空间中调用 /proc/&lt;pid&gt;/ns/mnt 绑定挂载确实不起作用。

    但是,ns/mnt 的绑定挂载在以下情况下有效:

    • mount() 是从具有另一个挂载命名空间的进程中调用的,
    • mount() 从正在挂载的ns/mnt 可见的进程中调用。

    如果在创建 ns/mnt 条目的 unshare() 调用之前派生的进程调用 mount(),则这两个要求都满足。

    (请注意, unshare() 调用之后,以前可见的ns/mnt 条目不再可见并成为损坏的符号链接)。

    这是一个测试:

    #define _GNU_SOURCE
    #include <limits.h>
    #include <string.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <sched.h>
    #include <sys/types.h>
    #include <sys/mount.h>
    
    int main(int argc, char** argv) {
        int fd = open("/tmp/mnt.ns", O_CREAT | O_RDWR);
        close(fd);
        if (argc > 1) {
            if (fork() == 0) {
                sleep(1);
            } else {
                unshare(CLONE_NEWNS);
                wait(NULL);
                return 0;
            }
        }
        char src[PATH_MAX] = {};
        snprintf(src, sizeof(src), "/proc/%u/ns/mnt", (unsigned)getppid());
        if (mount(src, "/tmp/mnt.ns", NULL, MS_BIND, NULL) != 0) {
            printf("mount failed: %s\n", strerror(errno));
            return 1;
        }
        else {
            printf("mount ok\n");
        }
        return 0;
    }
    

    没有fork()unshare(),此测试失败:

    $ sudo ./a.out  
    mount failed: Invalid argument
    

    但如果它在mount() 之前调用fork()unshare() 则有效(注意x arg):

    $ sudo ./a.out x
    mount ok
    

    请参阅 this commit 了解 unshare 工具以及 this patch

    很遗憾,ns/mnt 特有的这种行为未记录在 namespaces(7) 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      相关资源
      最近更新 更多