6
30
2014
0

open文件O_DIRECT方式打开问题

本文参考:

http://blog.csdn.net/wallwind/article/details/7461701

首先来看O_DIRECT参数适用要求:

O_DIRECT
    Try to minimize cache effects of the I/O to and from this file. In general this will degrade performance, but it is useful in special situations, such as when applications do their own caching. File I/O is done directly to/from user space buffers. The I/O is synchronous, i.e., at the completion of a read(2) or write(2), data is guaranteed to have been transferred. Under Linux 2.4 transfer sizes, and the alignment of user buffer and file offset must all be multiples of the logical block size of the file system. 

上述也就是说buffer的地址以及大小都必须是block size 的整数倍,buffer的大小可以通过代码设定,但buffer的首地址的控制,需要通过posix_menalign()函数来数据对齐

ps:上述所说的buffer地址为block size整数倍,就是数据对齐的概念

int posix_memalign (void **memptr, size_t alignment, size_t size);

成功会返回size字节的动态内存,且内存地址为alignment的整数倍

下面看具体代码

#define __USE_GNU
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int  main(void)
{
    int 		fd;
    int 		i;
    const int 	SIZE = 4096*10;//(每次写入文件数据块大小)
    char* 		buffer;
    char s[100];   
    int pagesize=getpagesize();
    printf("pagesize = %d\n",pagesize);
   pid_t my_pid;
    my_pid=getpid();
    printf("%d\n",my_pid);
	if(mkdir("dir1",S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH)<0)//创建新目录
	{
		printf("mkdir failed\n");
 		return -1;		
	}
	if(0 != posix_memalign((void**)&buffer, 4096, 40960)){
                printf("Errori in posix_memalign\n");
    }
 	for(i=0;i<10;i++)
	{
		sprintf(s,"./dir1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa%d.txt",i);
		printf("%s\n",s);
		fd=open(s, O_RDWR | O_CREAT | O_DIRECT);
		write(fd,buffer,SIZE);
                fsync(fd);
		close(fd);
	}
	free(buffer);
	sync();
	return 0;
}

上述代码有几个点:

1.mkdir创建目录

2.posix_menalign()进行数据对齐

3.获取block size,即内存页大小getpagesize()

4.编译时需要gcc -o blktrace_study1 blktrace_study1.c -D_GNU_SOURCE 

5.open函数返回的为int ,区别fopen函数返回FILE *

6.fsync和sync区别见另一篇博客

Category: Linux | Tags: | Read Count: 1577

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com