取消共享挂载命名空间后的文件访问

file access after unshare mount namespace

提问人:YAKOVM 提问时间:6/14/2022 最后编辑:YAKOVM 更新时间:6/14/2022 访问量:133

问:

我很高兴得到一个解释 unshar mount 命名空间的工作原理 对于以下代码:

unshare (mount_ns)
int pid = fork()
if (pid ==0)
{
   makedir("myDir");
   mount("path", "myDir", 0);
   int fd = open("myDir/myFile.txt", O_CREATE|O_RDWR);
   
   wrte(fd, "123\n",4);
   close(fd);
}
sleep(100000);
if(pid == 0)
{
   if (open("myDir/myFile.txt", O_RDONLY) < 0)
      printf ("son proc failed to read file\n");
   else
      printf ("son proc ok to read file\n");
}
else
{
    if (open("myDir/myFile.txt", O_RDONLY) < 0)
      printf ("parent proc failed to read file\n");
   else
      printf ("parent proc failed to read file\n");
}

我期望看到,但都成功了。取消分享后怎么可能?son proc ok to read fileparent proc failed to read file

Linux 挂载 取消共享

评论


答:

0赞 petitradisgris 6/14/2022 #1

我假设这是一个 C 代码。您提供的代码中似乎存在多个错误。

首先,您不会意识到父母成功读取文件,因为:

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc failed to read file\n");

应该是

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc ok to read file\n");

此外,也许以下几点:

int fd = open("myDir/myFile.txt", O_CREATE|O_RDWR);
wrte(fd, "123\n",4);

应为:

int fd = open("myDir/myFile.txt", O_CREAT|O_RDWR);
write(fd, "123\n",4);

此外:

如果在分叉之前取消共享挂载命名空间,则父级和子级都属于同一个挂载命名空间。

也许你应该把“取消分享(mount_ns)”移到其他地方,这样:

int pid = fork()
if (pid ==0) {
  unshare (mount_ns)
  makedir("myDir");
  ...

此致敬意。