【问题标题】:How can I exclude one file to be mounted from an entire disk如何从整个磁盘中排除要挂载的文件
【发布时间】:2020-02-01 19:08:02
【问题描述】:

我正在尝试使用 c++ 执行挂载,但我想排除一个正在挂载的特定文件,因为我不希望该文件被任何其他进程触及。

以下是我的源代码:

#include <sys/mount.h>

#define DROOT "/rd/daemon-root"

if (mkdir(DROOT, 0744) && errno != EEXIST)
    cout<<endl<<"Can't create "<<DROOT <<" (" << strerror(errno) << ")";

int r = mount("/", DROOT, "ext4", MS_BIND, NULL);
  if (r == -1)
    cout<<endl<<"Mounting of " DROOT " failed (" << strerror(errno) << ")";
  else
    cout<<endl<<DROOT<<" mounted successfully";

现在我的系统根目录包含 /etc 目录,我不希望它被挂载,因为使用挂载的进程会更改它。

有什么办法可以避免挂载特定目录,或者让它以一种方式改变,这样挂载上的更改就不会影响实际。

PS - 已经尝试过https://www.gnu.org/software/libc/manual/html_node/Mount_002dUnmount_002dRemount.html 列出的选项,但没有任何帮助。甚至没有 MS_ReadOnly

【问题讨论】:

    标签: c++ linux mount


    【解决方案1】:

    您不能排除单个文件。要排除一个目录,您可以在该目录顶部挂载一些东西以有效地隐藏它。但是,您必须小心确保仅隐藏绑定挂载中的目录,而不是原始目录中的目录。为此,您可以将第一个绑定挂载设为私有。使用 shell 命令,它看起来像这样:

    mkdir $DROOT
    mkdir /tmp/empty
    mount -o bind --make-private / $DROOT
    mount -o bind /tmp/empty $DROOT/tmp/
    

    在 C 中(减去错误检查):

    char path_to_hide[PATH_MAX];
    snprintf(path_to_hide, sizeof path_to_hide, "%s/%s", DROOT, "etc");
    
    mkdir(DROOT, 0744);
    mkdir("/tmp/empty", 0);
    
    mount("/", DROOT, NULL, MS_BIND | MS_PRIVATE, NULL);
    mount("/tmp/empty", path_to_hide, NULL, MS_BIND, NULL);
    

    【讨论】:

    • 感谢您的回答。我试过了,但如果在 DROOT/etc 内部有一些随机进程正在运行并在那里更改文件,那么原始 /etc 文件也会被更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2018-09-01
    相关资源
    最近更新 更多