文件描述符: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: