【发布时间】: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() 的返回值,只是为了简化代码,我没有在这里添加。