系统调用的效率底:
1.系统调用会影响系统的性能
与函数调用相比,在执行系统调用时,linux必须从运行用户代码切换到执行内核代码,
然后在返回用户代码。所以尽可能的减少系统调用的次数。
2.硬件一次读写的数据块是规定的
会导致留下过多的空隙导致空间浪费
系统调用与文件描述符:
1.系统调用一般通过文件描述符操作,文件描述符用来标记一个打开的文件或设备
2.一个程序运行时,它一般会有三个已经打开的文件描述符
0:标准输入
1:标准输出
2:标准错误
系统调用函数:
#include <unistd.h>
size_t write (int fildes, const void *buf, size_t nbytes);
把buf中前nbytes字节的数据写入与文件描述符fildes相关联的文件中
成功:返回实际写入的字节数
失败:返回-1错误代码保存在全局变量errno中
size_t read (int fildes, const void *buf, size_t nbytes);
与write相同
#include <fcntl.h>
#include <sys/types.h> //在遵循POSIX规范的系统上
#include <sys/stat.h> //不需要包含这两个文件
int open (const char *path, int oflags);
int open (const char *path, int oflags, mode_t mode);
成功:返回一个文件描述符(非负整数)
失败:返回-1错误代码保存在全局变量errno中
path:文件路径
oflags: A | B
A:O_RDONLY
O_WRONLY
O_RDWR
B: O_APPEND: 把写入的数据追加在文件的末尾
O_TRUNE: 清楚原有的文件内容
O_CREAT: 如果需要按mode中给出访问模式创建文件
O_EXCL: 与O_CREAT一起使用
......
mode: 与umask的反值的AND操作才是最后的权限结果
S_IRUSR: 读权限,文件属主
S_IWUSR:
S_IXUSR:
****GRP:
****OTH:
int creat (const char *path, mode_t mode);
相当于oflags为 O_CREAT| | O_WRONLY | O_TRUNC 来调用open
#include <unistd.h>
int close (int fildes);
返回0或-1
int ioctl (int fildes, int cmd, ...);
它是一个用于控制设备及其描述符行为和配置底层服务的!接口
#include <unistd.h>
#include <sys/types.h>
off_t lseek (int fildes, off_t offset, int whence);
设置fildes的读写指针设置
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
int fstat(ing fileds, struct stat *buf);
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
fstat系统调用返回与打开的文件描述符相关的文件的状态信息,
该信息将会写到一个buf结构中,buf的地址以参数形式传递给fstat
#include <unistd.h>
int dup(int fildes);
复制文件描述符,返回一个新的描述符
int dup2(int fildes, int fildes2); ????
把一个文件描述符复制为另外一个 ????
linux系统中各种文件函数与用户、设备驱动程序、内核和硬件之间的关系: