使用 C++ 在 Linux 中计算磁盘读/写

Posted

技术标签:

【中文标题】使用 C++ 在 Linux 中计算磁盘读/写【英文标题】:Calculating Disk Read/Write in Linux with C++ 【发布时间】:2013-01-25 15:57:16 【问题描述】:

我的要求是使用总磁盘读/写操作(或读/写的数据量)来分析当前进程的磁盘读/写操作。我需要每隔一秒采样一次并在这两者之间绘制一个图表。我需要在 C++ 中的 Linux (Ubuntu 12.10) 上执行此操作。

是否有任何 API/工具可用于此任务?我找到了一个工具,即iotop,但我不确定如何将其用于当前进程与系统范围的使用。

谢谢

【问题讨论】:

iotop 提供系统范围和每个进程的统计信息。它也是开源软件:您可以查看代码并了解他们是如何做到的。 (不过,如果您复制任何代码,请务必遵守许可条款。) 您可以查看conky 的源代码 - 它完全符合您的要求。 【参考方案1】:

您可以每秒读取文件/proc/diskstats。每行代表一个设备。

来自内核的“Documentation/iostat.txt”:

Field  1 -- # of reads completed
    This is the total number of reads completed successfully.
Field  2 -- # of reads merged, field 6 -- # of writes merged
    Reads and writes which are adjacent to each other may be merged for
    efficiency.  Thus two 4K reads may become one 8K read before it is
    ultimately handed to the disk, and so it will be counted (and queued)
    as only one I/O.  This field lets you know how often this was done.
Field  3 -- # of sectors read
    This is the total number of sectors read successfully.
Field  4 -- # of milliseconds spent reading
    This is the total number of milliseconds spent by all reads (as
    measured from __make_request() to end_that_request_last()).
Field  5 -- # of writes completed
    This is the total number of writes completed successfully.
Field  7 -- # of sectors written
    This is the total number of sectors written successfully.
Field  8 -- # of milliseconds spent writing
    This is the total number of milliseconds spent by all writes (as
    measured from __make_request() to end_that_request_last()).
Field  9 -- # of I/Os currently in progress
    The only field that should go to zero. Incremented as requests are
    given to appropriate struct request_queue and decremented as they finish.
Field 10 -- # of milliseconds spent doing I/Os
    This field increases so long as field 9 is nonzero.
Field 11 -- weighted # of milliseconds spent doing I/Os
    This field is incremented at each I/O start, I/O completion, I/O
    merge, or read of these stats by the number of I/Os in progress
    (field 9) times the number of milliseconds spent doing I/O since the
    last update of this field.  This can provide an easy measure of both
    I/O completion time and the backlog that may be accumulating.

对于每个进程,您可以使用/proc/<pid>/io,它会产生如下内容:

rchar: 2012
wchar: 0
syscr: 7
syscw: 0
read_bytes: 0
write_bytes: 0
cancelled_write_bytes: 0
rchar、wchar:读/写的字节数。 syscr、syscw:读/写系统调用次数。 read_bytes, write_bytes:读/写到存储介质的字节数。 cancelled_write_bytes:据我所知,是由调用“ftruncate”取消挂起的对同一文件的写入引起的。可能最常见的是 0。

【讨论】:

Linux 磁盘统计中的扇区有多大?消息lkml.org/lkml/2015/8/17/269的作者对吗? 我当然不比那封邮件的作者更专业,所以除非最近有任何变化,否则我没有理由不同意。 Theodor Ts'o 是 Linux 内核社区的创始成员之一,从“一开始”就一直致力于内核的开发。 那么,/proc/diskstats 的扇区大小仍然是 512 字节?

以上是关于使用 C++ 在 Linux 中计算磁盘读/写的主要内容,如果未能解决你的问题,请参考以下文章

使用C直接读/写磁盘[重复]

测量读/写磁盘利用率

如何在 Linux 上获取磁盘信息?

已解决Linux中buff/cache(磁盘写/读缓存)占用大量内存导致用户进程内存不足

Linux系统磁盘管理(实操演示磁盘分区创建,文件系统的挂载与自动挂载)

如果使在Linux中修改的数据不回写到磁盘?