linux直接IO代码演示
2021/6/29 7:22:16
本文主要是介绍linux直接IO代码演示,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
点击查看代码
#define _GNU_SOURCE//第一步,定义这个宏 #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<string.h> #include<errno.h> int main() { char*buff=NULL; const char* fileName="./directIO.txt"; int fd=0; /* 第二步,使用posix_memalign分配内存 因为直接IO直接往磁盘里读写数据,磁盘是块设备,以扇区为最小单位,大小为512个字节,需要内存边界对齐 所以第二个参数设置成512,第三个参数需要满足是第二个参数的倍数等其他条件,具体可查看linux帮助手册 */ posix_memalign((void**)&buff,512,512); strcpy(buff,"it's not just a test,man\n"); //第三步,文件打开方式必须加上O_DIRECT fd=open(fileName,O_RDWR|O_CREAT|O_APPEND|O_DIRECT,S_IRWXU|S_IRWXG|S_IRWXO); if(fd<0) { fprintf(stderr,"open file fail,reason:%s\n",strerror(errno)); return -1; } for(int i=0;i<10;i++) { int len=0; /* 写入的字符可能需要是512的倍数 (根据硬件吧或者其他情况,因为我看别人写入其他数量的字符也成功了,但是我就失败了,"invalid parameter") */ if((len=write(fd,buff,512))<0) { fprintf(stderr,"write error,reason:%s\n",strerror(errno)); } else { printf("%d\n",i); } } if(buff) { free(buff); buff=NULL; } printf("start to sleep 10 seconds...\n"); sleep(10); close(fd); return 0; }
这篇关于linux直接IO代码演示的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-0600-macOS和Linux安装和管理多个Python版本
- 2024-03-30[译]漫画SELinux概念
- 2024-03-29linux 移动文件
- 2024-03-28linux .so file
- 2024-03-28Linux 磁盘管理
- 2024-03-28Linux学习笔记(十三)磁盘管理(一):磁盘分区
- 2024-03-26linux 创建 文件
- 2024-03-25使用SecureCRT对Linux vim进行颜色设置
- 2024-03-202019-2020-12 20199317 《Linux内核原理与分析》 第十二周作业
- 2024-03-20Linux运维的第二周总结