cp命令
cp source_file target_file
能夠復制文件,如果target_file所指定的文件不存在,cp就創建這個文件,如果已經存在,就把文件內容清空並把source_file的內容添加到target_file中。
cp命令的工作流程
open sourcefile for reading
open targetfile for writing
+--> read from source to buffer ---- eof ? --- +
| |
----- write from buffer to copy <------------- +
close sourcefile
close targetfile
1 #include <stdio.h> 2 #include <fcntl.h> 3 #include <unistd.h> 4 #include <stdlib.h> 5 6 #define BUFFERSIZE 4096 7 #define COPYMODE 0644 8 9 void oops(char *s1, char *s2); 10 int main(int ac,char *av[]) 11 { 12 int in_fd,out_fd,n_chars; 13 char buf[BUFFERSIZE]; 14 15 if(ac != 3) 16 { 17 fprintf(stderr,"usage:%s source destination\n",*av); 18 exit(1); 19 } 20 21 if( (in_fd = open(av[1],O_RDONLY)) == -1) 22 { 23 oops("Cannot open" , av[1]); 24 } 25 26 if( (out_fd = creat(av[2],COPYMODE)) == -1 ) 27 { 28 oops("Cannot open" , av[2]); 29 } 30 31 while( ( n_chars = read(in_fd,buf,BUFFERSIZE)) > 0 ) 32 if( (write(out_fd,buf,n_chars)) != n_chars) 33 oops("Write error to ", av[2]); 34 35 if(n_chars == -1) 36 oops("Read error from ",av[1]); 37 38 if(close(in_fd) == -1 || close(out_fd) == -1) 39 oops("Error closing files",""); 40 41 } 42 43 void oops(char *s1, char *s2) 44 { 45 fprintf(stderr,"Error:%s",s1); 46 perror(s2); 47 exit(1); 48 49 }
效果如下
使用到的函數:
1.int fd = creat(char * filename, mode_t mode)
creat告訴內核創建一個filename的文件,如果不存在,則直接創建,如果存在,則先把文件的內容清空,把文件長度設置為0。並且把文件的權限設置為mode
2.ssize_t result = write(int fd,void * buf,size_t amt)
write這個系統調用告訴內核把數據寫入文件中,如果寫入失敗返回 -1 ,成功返回寫入的字節數。
cp命令的分析
1. 緩沖區的影響
緩沖區的大小對我們這個程序的運行速度是有影響的,舉一個例子:用小勺子把湯從一個碗里盛到另一個碗里,可能要盛十幾次,當換成一個大一點的勺子,可能只需要幾次。
2. 系統調用的開銷
使用系統調用會消耗很多時間,用戶進程位於用戶空間,內核進程位於內核空間,磁盤只能被內核直接訪問。當我們要讀取文件時,需要使用系統調用read,而read在內核空間中,因此,執行的時候是從用戶空間切換到內核空間,這是需要時間的。為什么需要時間?當CPU從用戶模式切換到管理員模式時,需要進行一些環境的配置,如一些特殊的堆棧和內存環境。當使用完系統調用時,CPU就又要從管理員模式切換到用戶模式,也需要花費一些時間,因此,在一些程序中應該節約類似於模式切換的開銷。
本篇筆記自拜讀《 Unix/Linux編程實踐教程》
我也推薦和我一樣的初學者去拜讀這本書,讓你對linux有可下手的地方。