Buffered I/O and non-buffered I/O

来源:互联网 发布:淘宝订单改价有影响吗 编辑:程序博客网 时间:2024/05/16 17:43

Buffered I/O and non-buffered I/O

转自:http://ender.hitidea.org/tag/o_direct/

参考文献部分的内容是非常好的。这个选项在测试时是非常有用的。

实验需要对Flash Disk做无系统缓冲的I/O操作,顺便了解了一下Linux下的I/O.

Linux上的块设备的操作可以分为两类:

  • 第一类是使用C标准库中的fopen/fread/fwrite 系列的函数,我们可以称其为 buffered I/O。

具体的I/O path如下

Application<->Library Buffer<->Operation System Cache<->File System/Volume Manager<->Device

 

library buffer是标准库提供的用户空间的buffer,可以通过setvbuf改变其大小。

  • 第二类是使用Linux的系统调用的open/read/write 系列的函数,我们可以称其为 non-buffered I/O。

I/O Path

Application<-> Operation System Cache <->File System/Volume Manager<->Device

 

此外,我们可以通过设置open的O_DIRECT标志来实现Direct I/O(或者叫Raw I/O),即绕过OS Cache,直接读取Device ( that’s what we want^o^ ), 等于将OS cache换成自己管理的cache。不过,Linus在邮件列表中建议不这么做,而是使用posix_fadvice, madvice。[2]中表明Direct I/O比buffered I/O的性能高很多。

在使用O_DIRECT的注意buffer的address必须是block alignment的(i.e. 初始地址必须是boundary), 可以用posix_memalign()函数分配内存以得到这样的buffer。至于为什么要这样,与实现的mmap有关,参见[5].

参考:

  1. Linux: Accessing Files With O_DIRECThttp://kerneltrap.org/node/7563
  2. Andrea Arcangeli , O_DIRECT Whitepaperhttp://www.ukuug.org/events/linux2001/papers/html/AArcangeli-o_direct.html
  3. A Trip Down the Data Path: I/O and Performancehttp://articles.directorym.net/_A_Trip_Down_the_Data_Path_IO_and_Performance-a894569.html
  4. Operating Systems System Calls and I/Ohttp://articles.directorym.net/Operating_Systems_System_Calls_and_IO-a894576.html
  5. Linux Device Drivers, 2nd Edition, Chapter 13 mmap and DMAhttp://www.xml.com/ldd/chapter/book/ch13.html
  6. http://topic.csdn.net/u/20080806/10/cdb1faa1-0146-4e96-8b12-26ba60acdbb5.html
  7. http://lists.alioth.debian.org/pipermail/parted-devel/2007-July/thread.html#1855
  8. Read系统调用剖析,http://www.ibm.com/developerworks/cn/linux/l-cn-read/
在编写程序中出现的问题:
Problem:使用O_DIRECT标志打开文件,但是编译器报告O_DIRECT不认识。
Solution:在#include<fcntl.h>前要添加#define __USE_GNU 1,否则O_DIRECT没有定义。还有就是文件读写的缓冲区要用posix_memalign对齐(2.6中是512字节),文件读写的大小也要是512对齐的。