1

以下简单的 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)——这可能与它有关吗?

4

1 回答 1

1

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

mount("none", "/", NULL, MS_PRIVATE | MS_REC, NULL);
于 2016-05-24T07:53:31.653 回答