【问题标题】:unshare system call doesn't work取消共享系统调用不起作用
【发布时间】:2016-05-18 13:35:39
【问题描述】:

以下简单的 C++ 程序尝试取消共享安装空间,安装 USB 存储设备(位于 /dev/sdd),等待输入,然后卸载该设备。

#include <iostream>
#include <stdio.h>
#include <exception>
#include <algorithm>
#include <vector>
#include <limits> 
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    unshare(CLONE_NEWNS);

    pid_t pid = fork();

    if (0 == pid)
    {
        char * mount_args[] = {"/bin/mount", "--make-rprivate", "/dev/sdd", "/mnt", "-o,ro", "-o,noexec", NULL};

        if (0 > execv("/bin/mount", mount_args))
        {
            perror("execv: ");
            exit(1);
        }
        //this line will never be reached.
        return 0;
    }
    else if (0 < pid)
    {
        //parent process!
        int status = -1;
        wait(&status);

        if (0 == status)
        {
            std::cout << "press ENTER to continue....";
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

            char * umount_args[] = {"/bin/umount", "/mnt", NULL};
            if (0 > execv("/bin/umount", umount_args))
            {
                perror("execv: ");
                exit(1);
            }
        }
        return status;
    }
    else
    {
        //fork error!
        perror("fork!\n");
        exit(1);
    }
    return 0;
}

但是,当我运行它时(在使用 -fpermissive 编译之后),系统上的所有其他进程都可以看到挂载。

我的目标,即我的挂载对其他用户空间进程不可见,显然没有实现。

我做错了什么?

编辑:此代码不适用于 Ubuntu 16.04(内核版本 4.4)。它确实适用于 Ubuntu 14.04(内核版本 4.2)——这可能与它有关吗?

【问题讨论】:

  • 也许你有权挂载它(根据/etc/fstab)但不能卸载它?
  • 你没有检查unshare()的返回值,也没有检查wait()的返回值...
  • 你为什么使用CLONE_NEWNS?另外,为什么致电umount()linux.die.net/man/2/umount
  • 我确实有权挂载(我以 root 身份运行可执行文件)。
  • 我确实检查了 unshare() 和 wait() 的返回值,只是为了简化代码,我没有在这里添加。

标签: linux mount umount


【解决方案1】:

原来操作系统默认挂载选项在 Ubuntu 16 中已更改。为了使 unshare(2) 正常工作,您需要在代码中添加以下行(在 unshare 之前):

mount("none", "/", NULL, MS_PRIVATE | MS_REC, NULL);

【讨论】:

  • 谢谢你!命令行上的等价物,使用mount(8)unshare(1) 是:mount --make-rprivate none / &amp;&amp; unshare --mount program [args]
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2012-09-08
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
相关资源
最近更新 更多