使用不同的安装命名空间在Linux中创建进程

时间:2016-07-11 16:19:56

标签: linux

我正在尝试创建一个与其父级具有不同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)行。

对此有何解释?

1 个答案:

答案 0 :(得分:0)

您需要将现有坐标标记为&#34; private&#34;在创建新命名空间之前:

mount --make-rprivate /