#include <stdio.h>#include <stddef.h>#include <dirent.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <linux/fcntl.h>#define BLOCK_SIZE 4096intmain(intargc,char*argv[]){intfhInput;intfhOutput;intlen;intsum;staticunsignedcharbuf[BLOCK_SIZE]__attribute__((aligned(4096)));if(argc==3){fhInput=open(argv[1],O_RDONLY|O_DIRECT);fhOutput=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC|O_DIRECT);if((fhInput<0)||(fhOutput<0)){printf("[Error] open file fail.\n");if(fhInput>=0){close(fhInput);}else{printf("[Error] Can not open %s\n",argv[1]);}if(fhOutput>=0){close(fhOutput);}else{printf("[Error] Can not open %s\n",argv[2]);}return-1;}else{sum=0;do{len=read(fhInput,buf,BLOCK_SIZE);//printf("len: %d\n",len);write(fhOutput,buf,BLOCK_SIZE);sum+=BLOCK_SIZE;}while(len==BLOCK_SIZE);if(len>0){ftruncate(fhOutput,sum-BLOCK_SIZE+len);}structstatfileAttr;fstat(fhInput,&fileAttr);fchmod(fhOutput,fileAttr.st_mode);close(fhOutput);close(fhInput);return0;}}else{printf("[help] ./my_copy ./src_file ./dest_file \n");return-1;}}
編譯與執行:
Terminal
12345678910111213
bramante@matrix:~/test$ gcc -o ./my_copy ./my_copy.c
bramante@matrix:~/test$ which ls
/bin/ls
bramante@matrix:~/test$ ll /bin/ls
-rwxr-xr-x 1 root root 105840 Nov 20 2012 /bin/ls*
bramante@matrix:~/test$ ./my_copy /bin/ls ./ls
bramante@matrix:~/test$ ll | grep ls
-rwxr-xr-x 1 bramante bramante 105840 Sep 4 11:15 ls*
bramante@matrix:~/test$ diff ./ls /bin/ls
bramante@matrix:~/test$
bramante@matrix:~/test$ ./ls -al | grep ls
-rwxr-xr-x 1 bramante bramante 105840 Sep 4 11:15 ls
bramante@matrix:~/test$
Direct IO 所read/write的byte數, 以及read/write的起點,
還有read()/write()所使用的memory buffer, 應該都要align在512 byte的倍數上,
精確的alignment限制可以參考網路上的說明: