繁体   English   中英

使用C用户空间代码从Linux / proc接口读取的最佳方法是什么?

[英]What is the best way to read from Linux /proc interfaces using C user space code?

根据man 5 proc ,可以使用/proc文件系统访问Linux上的以下信息:

   /proc/[pid]/maps
          A file containing the currently mapped memory regions and their access
          permissions.

          The format is:

          address           perms offset  dev   inode   pathname
          08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
          08056000-08058000 rw-p 0000d000 03:0c 64593   /usr/sbin/gpm
          08058000-0805b000 rwxp 00000000 00:00 0
          40000000-40013000 r-xp 00000000 03:0c 4165    /lib/ld-2.2.4.so
          40013000-40015000 rw-p 00012000 03:0c 4165    /lib/ld-2.2.4.so
          4001f000-40135000 r-xp 00000000 03:0c 45494   /lib/libc-2.2.4.so
          40135000-4013e000 rw-p 00115000 03:0c 45494   /lib/libc-2.2.4.so
          4013e000-40142000 rw-p 00000000 00:00 0
          bffff000-c0000000 rwxp 00000000 00:00 0

          where "address" is the address space in the process that it occupies,
          "perms" is a set of permissions:

               r = read
               w = write
               x = execute
               s = shared
               p = private (copy on write)

          "offset" is the offset into the file/whatever, "dev" is the device
          (major:minor), and "inode" is the inode on that device.  0 indicates
          that no inode is associated with the memory region, as the case would
          be with BSS (uninitialized data).

          Under Linux 2.0 there is no field giving pathname.

我真的不想在C中编写文本解析代码; 我宁愿只是调用操作系统并直接将信息读入结构中。 我查看了/usr/include/linux ,看看是否有一个明显的API结构,但没有看到任何东西。

那么,两部分问题:

  1. 这可以被认为是一个“坏主意”吗? 也就是说,如果内核接口发生变化,用户程序是否应该咬住子弹并从/proc读取文本? 如果是这样,是否有一个被接受的“最佳实践”来使用C读取/proc fscanf() ?正则表达式?)
  2. 我如何找到内核接口的文档(假设它们存在),这将允许我直接读取这些数据? (内核源代码本身是最好的起点吗?如果是这样,我应该在内核源代码中查找哪些内容?)如果您知道哪个接口可以提供/proc/[pid]/maps数据,则可以获得奖励积分。 =)

我认为对于perl或shell脚本来说,读取和解析/ proc / data非常好。 在C程序中,如果需要健壮性,我会使用内核(可能是一个sysctl )接口。

事实证明, procps-bundled pmap实现逐行解析/proc/PID/maps文件,如下所示(参见one_proc()函数):

sscanf(mapbuf,"%"KLF"x-%"KLF"x %31s %Lx %x:%x %Lu", &start, &end, flags, &file_offset, &dev_major, &dev_minor, &inode);

编辑 :我的答案的原始版本显示了一种方法来解析共享内存段上的数据,而不是所有映射的内存段作为OP所需。

我相信ipcs -m会为多个进程提供相同的数据。 所以你的第二个问题的答案是你应该阅读ipcs代码:(例如BSD版本Linux版本 ):

在Linux上,顺序读取像/proc/self/maps这样的文本伪文件是获取该信息的规范方式(并且没有简单的方法来获取它;这是内核提供它的方式。)。

您可以使用一些库(如libproc )为您执行此操作。 但最终您的应用程序将在/proc下解析(可能通过一些库)文件。 我不确定你是否应该避免这种情况。

只是尝试运行像pstop这样的命令,其中/proc被卸载。 它可能不再适用了。

libproc提供了一种访问/proc下的内容的便捷方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM