c - linux函数获取挂载点

标签 c linux mount libc

标准 Linux 库中是否有函数(或接口(interface);ioctl、netlink 等)可以直接从内核返回当前挂载而不解析/proc? strace挂载命令,看起来是解析/proc中的文件

最佳答案

Please see the clarification at the bottom of the answer for the reasoning being used in this answer.

您有什么理由不使用 getmntent libc 库调用?我确实意识到它与“一体式”系统调用不同,但它应该能让您获得相关信息。

#include <stdio.h>
#include <stdlib.h>
#include <mntent.h>

int main(void)
{
  struct mntent *ent;
  FILE *aFile;

  aFile = setmntent("/proc/mounts", "r");
  if (aFile == NULL) {
    perror("setmntent");
    exit(1);
  }
  while (NULL != (ent = getmntent(aFile))) {
    printf("%s %s\n", ent->mnt_fsname, ent->mnt_dir);
  }
  endmntent(aFile);
}

澄清

考虑到 OP 澄清了如何安装 /proc 尝试执行此操作,我将澄清:

There is no facility outside of /proc for getting the fully qualified list of mounted file systems from the linux kernel. There is no system call, there is no ioctl. The /proc interface is the agreed upon interface.

话虽如此,如果你没有安装/proc,你将不得不解析/etc/mtab文件——传入/etc/mtab 而不是 /proc/mounts 到初始 setmntent 调用。

mountunmount 命令在文件中维护当前已安装文件系统的列表/etc/mtab.这在几乎所有 linux 中都有详细说明/unix/bsd这些命令的手册页。因此,如果您没有 /proc,您可以某种程度上依赖此文件的内容。它不能保证是真理的来源,但惯例就是这些事情的惯例。

因此,如果您没有/proc,您可以在下面的getmntent libc 库调用中使用/etc/mtab 来获取文件系统列表;否则,您可以使用 /proc/mounts/proc/self/mountinfo 之一(现在推荐使用 /proc/mounts)。

关于c - linux函数获取挂载点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9280759/

相关文章:

c - 为什么在我使用归并排序时,一个额外的元素被添加到我的 void** 数组中?

linux - Ubuntu 12.04 fstab 损坏

linux - 不知道如何在 ubuntu 中挂载文件系统

linux - 在安装过程中将 R 包链接到 Linux RPM

linux - 向 postfix 中的组发送邮件

c - Linux 驱动程序 : Copy memory from different user-process

Linux: "fstab"有额外的挂载选项吗?

c - 我如何暂停子进程并重置它

c - .dat 文件中的 fread()

c++ - 用于包装采用 void* 参数的 C 回调的模板魔术?