【发布时间】:2021-07-01 03:15:44
【问题描述】:
我的程序调用clone,在子进程中调用/bin/sh。
在 shell 中,我运行 cat /proc/$$/mountinfo 来查看传播属性。
如果标志是CLONE_NEWNS,我得到了这个:
# cat /proc/$$/mountinfo
194 193 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw,discard,errors=remount-ro
...
如果结合CLONE_NEWNS 和CLONE_NEWUSER(在以下来源中取消注释flags |= CLONE_NEWUSER;),我得到了这个:
199 198 8:1 / / rw,relatime master:1 - ext4 /dev/sda1 rw,discard,errors=remount-ro
...
为什么CLONE_NEWUSER 会有所作为?在我的机器 (Debian 9) 上,它应该始终是 MS_SHARED,因为它是从 MS_SHARED 安装点创建的。
#define _GNU_SOURCE
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define STACK_SIZE (1024 * 1024)
static char container_stack[STACK_SIZE];
char *const container_args[] = {"/bin/sh", NULL};
int container_main(void *arg) {
printf("Container - inside the container!\n");
printf("container pid is %d\n", getpid());
int status = execv(container_args[0], container_args);
if (status < 0) perror("execv");
printf("Something's wrong!\n");
return 0;
}
int main() {
printf("Parent [ %d ] - start a container!\n", getpid());
int flags = CLONE_NEWNS;
//flags |= CLONE_NEWUSER;
int container_pid = clone(container_main, container_stack + STACK_SIZE,
SIGCHLD | flags, NULL);
if (container_pid < 0) {
perror("clone");
return -1;
}
printf("Container pid is %d\n", container_pid);
waitpid(container_pid, NULL, 0);
printf("Parent - container stopped!\n");
return 0;
}
【问题讨论】:
标签: c linux containers