1. Linux 文件系统基本概念
2.文件IO 访问方式概述
注意:
更好的方式: 缓存同步
缓存同步 -为了保证磁盘系统与缓冲区中内容一致,Linux 系统提供了 sync、fsync 和fdatasync 三个
函数.
函数描述:向打开的文件写数据; 成功返回写入的字节数,若出错,返回-1。
头文件:#include <unistd.h>
int fsync(int fd);
int fdatasync(int fd);
void sync(void);
说明: sync - 将所有修改过的块缓冲区排入写队列,然后就返回,它并不等待实际写磁盘操作结束。
fsync - 将fd对应文件的块缓冲区立即写入磁盘,并等待实际写磁盘操作结束返回。
fdatasync - 类似fsync,但只影响文件的数据部分。而除数据外,
fsync 还会同步更新文件属性。
Linux 文件IO流程图
3.血案还会缠身吗
例子:
#define _GNU_SOURCE //直接IO需要的宏
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define BUF_LEN 512
int debug =0;
//文件直接IO
int main(int argc, char* argv[]){
char *buf=NULL;
const char * fileName="./wirte.txt";
int fd = -1;
time_t start cur;
int rlen=0;
int ret=0;
static int read_total=0;
ret = posix_memalign((void **)&buf,512,BUF_LEN);
if(ret!=0){
fprintf(stderr,"posix_memalign failed; reason: %s\n",strerror(errno));
}
start = time(NULL);
do{
read_total++;
//直接IO
fd = open(fileName,O_RDWR | O_DIRECT);
//标准IO
//fd = open(fileName,O_RDWR);
if(fd<0){
fprintf(stderr,"fopen %s failed, reason: %s \nexit. \n",fileName,strerror(errno));
return -1;
}
getchar();
do{
if((rlen = read(fd,buf,BUF_LEN))<0){
fprintf(stderr,"read from %s failed , reason:%s. \nexit, \n",fileName,strerror(errno));
}
if(debug){
printf("read : %d\n",rlen);
}
}while(rlen>0);
printf("finished...\n");
int ret=0;
//如果返回0表示数据从缓存区成功写入到设备
//返回-1表示从缓存区写入到设备失败,但数据不会丢失,下次接着写入;
ret = fsync(fd);
if(ret!=0){
printf("文件写入失败!!");
}
close(fd);
cur=time(NULL);
}while((cur-start)<20);
printf("total num:%d\n",read_total);
return 0;
}
注意: linux系统的防火墙不关闭的话samba 服务器是连接不上的;
查看防火墙的: ufw status;
关闭防火墙: ufw disable;
打开防火墙:ufw enable;