【问题标题】:Creating a process in Linux with a different mount namespace在 Linux 中使用不同的挂载命名空间创建进程
【发布时间】:2016-11-13 16:21:03
【问题描述】:

我正在尝试创建一个具有与其父级不同的 mnt 命名空间的进程。

为此,我使用以下代码:

static int childFunc(void *arg){
    if (mount("/","/myfs", "sysfs", 0, NULL) == -1) 
        errExit("mount");
    printf("Starting new bash. Child PID is %d\n",getpid());
    execle("/bin/bash",NULL);
    printf("Shouldn't arrive here.\n");
    return 0;           /* Child terminates now */
}

#define STACK_SIZE (1024 * 1024)    /* Stack size for cloned child */

int main(int argc, char *argv[]){
    char *stack;                    /* Start of stack buffer */
    char *stackTop;                 /* End of stack buffer */
    pid_t pid;

    /* Allocate stack for child */
    stack = malloc(STACK_SIZE);
    if (stack == NULL)
        errExit("malloc");
    stackTop = stack + STACK_SIZE;  /* Assume stack grows downward */

    /* Create child that has its own MNT namespaces*/
    pid = clone(childFunc, stackTop, CLONE_NEWNS | SIGCHLD, argv[1]);
    if (pid == -1)
        errExit("clone");
    printf("clone() returned %ld\n", (long) pid);
    sleep(1); 

    if (waitpid(pid, NULL, 0) == -1)    /* Wait for child */
        errExit("waitpid");
    printf("child has terminated\n");
    exit(EXIT_SUCCESS);
}

运行它时,我确实得到了一个 bash shell,它在不同的 MNT 命名空间中运行。 为了验证,我在另一个shell中执行sudo ls -l /proc/<child_pid>/ns,我确实看到子进程与系统中的其他进程有不同的命名空间。

但是,如果我从两个 shell 执行 mount - 我会得到相同的 FSTAB 输出,并且行 myfs on /myfs type sysfs (rw,relatime) 出现在它们两个中。

对此有何解释?

【问题讨论】:

    标签: linux


    【解决方案1】:

    在创建新命名空间之前,您需要将现有的挂载标记为“私有”:

    mount --make-rprivate /
    

    【讨论】:

    • 我得承认我不知道怎么做。我还认为,此操作应由管理员完成,而不是由进程隐式执行,因为它会影响整个系统。但可以肯定的是,mount 是用C 写的,所以有办法。我建议阅读mount 命令的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多