文件描述符:shell
open和openat函数:数据结构
creat函数:app
lseek函数:
1. 用于显式指定被打开文件的偏移量,返回当前文件的新偏移量;
2. 测试标准输入是否能够seek:异步
1 #include "apue.h" 2 3 int main(void) 4 { 5 if (lseek(STDIN_FILENO, 0, SEEK_CUR) == -1) { 6 printf("canot seek\n"); 7 } 8 else { 9 printf("seek OK\n"); 10 } 11 exit(0); 12 }
3. 因为文件当前偏移量可能为负数,lseek的返回值应该和 -1 比较,而不是测试是否小于0;
4. 设置的当前文件偏移量大于文件长度时,文件中容许造成空洞,空洞不须要存储空间来存储;
5. 在文件中建立一个空洞:async
1 #include "apue.h" 2 #include <fcntl.h> 3 4 char buf1[] = "abcdefghij"; 5 char buf2[] = "ABCDEFGHIJ"; 6 7 int main(void) 8 { 9 int fd; 10 11 if ((fd = creat("file.hole", FILE_MODE)) < 0) { 12 err_sys("creat error"); 13 } 14 15 if (write(fd, buf1, 10) != 10) { 16 err_sys("buf1 write error"); 17 } 18 /*offset now = 10*/ 19 20 if (lseek(fd, 16384, SEEK_SET) == -1) { 21 err_sys("lseek error"); 22 } 23 /*offset now = 16384*/ 24 25 if (write(fd, buf2, 10) != 10) { 26 err_sys("buf2 write error"); 27 } 28 29 exit(0); 30 }
read/write函数:ide
I/O效率:
1. 利用缓冲将标准输入复制到标准输出:函数
1 #include "apue.h" 2 3 #define BUFFSIZE 4096 4 5 int main(void) 6 { 7 int n; 8 char buf[BUFFSIZE]; 9 10 while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0) { 11 if (write(STDOUT_FILENO, buf, n) != n) { 12 err_sys("write error"); 13 } 14 } 15 if (n < 0) { 16 err_sys("read error"); 17 } 18 19 exit(0); 20 }
2. Linux ext4文件系统,块大小是4096,缓冲大小最佳值是4096。
文件共享:
1. 内核使用三个数据结构表示打开的文件:工具
原子操做:测试
dup和dup2函数:ui
sync, fsync和fdatasync函数:
fcntl函数:
1. fcntl函数能够改变一个已打开文件的属性;
2. fcntl函数有5种不一样功能:
3. 打印具体描述符的文件标志:
1 #include "apue.h" 2 #include <fcntl.h> 3 4 int main(int argc, char *argv[]) 5 { 6 int val; 7 if (argc != 2) { 8 err_quit("usage: a.out <descriptor#>"); 9 } 10 11 if ((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0) { 12 err_sys("fcntl error for fd %d", atoi(argv[1])); 13 } 14 switch(val & O_ACCMODE) { 15 case O_RDONLY: 16 printf("read only"); 17 break; 18 case O_WRONLY: 19 printf("write only"); 20 break; 21 case O_RDWR: 22 printf("read write"); 23 break; 24 default: 25 err_dump("unknow access mode"); 26 } 27 if (val & O_APPEND) { 28 printf(",append"); 29 } 30 if (val & O_NONBLOCK) { 31 printf(",nonblocking"); 32 } 33 if (val & O_SYNC) { 34 printf(",synchronous writes"); 35 } 36 #if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC) && (O_FSYNC != O_SYNC) 37 if (val & O_FSYNC) { 38 printf(",synchronous writes"); 39 } 40 #endif 41 putchar('\n'); 42 43 exit(0); 44 }
4. 打开文件描述符的一个或者多个文件状态标志:
1 #include "apue.h" 2 #include <fcntl.h> 3 4 void set_fl(int fd, int flags) 5 { 6 int val; 7 if ((val = fcntl(fd, F_GETFL, 0)) < 0) { 8 err_sys("fcntl F_GETFL error"); 9 } 10 val |= flags; 11 if (fcntl(fd, F_SETFL, val) < 0) { 12 err_sys("fcntl F_SETFL error"); 13 } 14 }
ioctl函数:
/dev/fd: