由于最近毕设用到了文件系统相关的知识,所以今天把文件系统的知识再巩固一下,最近要查找文献,写论文,所以不定期更新。本期内容在之前的博客中已有相关,大家可以翻阅。
1.系统调用
1、Unix/Linux大部分系统功能是通过系统调用实现的,如open/close。
2、Unix/Linux的系统调用已被封装成C函数的形式,但它们并不是标准C的一部分。
3、标准库函数大部分时间运行在用户态,但部分函数偶尔也会调用系统调用,进入内核态,如malloc/free。
4、程序员自己编写的代码也可以调用系统调用,与操作系统内核交互,进入内核态,如brk/sbrk/mmap/munmap。
5、系统调用在内核中实现,其外部接口定义在C库中,该接口的实现借助软中断进入内核。
•time命令:测试运行时间
•real : 总执行时间
•user : 用户空间执行时间
•sys : 内核空间执行时间
•strace命令:跟踪系统调用
2.文件系统相关调用
1.open - 打开/创建文件
2.creat - 创建空文件
3.close - 关闭文件
4.read - 读取文件
5.write - 写入文件
6.lseek - 设置读写位置
7.fcntl - 修改文件属性
8.unlink - 删除硬链接
9.rmdir - 删除空目录
10.remove - 删除硬链接(unlink)或空目录(rmdir)
3.文件描述符
内核(kernel)利用文件描述符(file descriptor)来访问文件。文件描述符是非负整数。
打开现存文件或新建文件 时,内核会返回一个文件描述符。
读写文件也需要使用文件描述符来指定待读写的文件。
4.文件系统使用
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
struct Stu
{
char name[20];
size_t age;
int grade[3];
};
int judge(int fd,char *s){
if(fd == -1){
perror(s);
return -1;
}
}
int main(){
int fd = open("study.txt",O_CREAT|O_WRONLY|O_TRUNC,644);
/*
if(fd == -1){
perror("open");
return -1;
}*/
judge(fd, "open");
printf("open succeed!\n");
struct Stu s = {"ycj",18,{100,100,88}};
ssize_t res = write(fd,&s,sizeof(s));
/*
if(res == -1 ){
perror("write");
return -1;
}
*/
judge(res, "write");
printf("write succeed!\n");
res = close(fd);
/*
if(fd == -1 ){
perror("close");
return -1;
}
*/
judge(fd, "close");
fd = open("study.txt", O_RDONLY);
res = read(fd, &s, sizeof(s));
judge(fd, "read");
printf("%s %u\n",s.name,s.age);
printf("%d %d %d\n",s.grade[0],s.grade[1],s.grade[2]);
res = close(fd);
return 0;
}