怎么设立网站赚广告费,网站设计公司模板下载,电子商务网站设计与实现论文,王烨华摘要#xff1a;linux中cp命令的实现#xff0c;通过这个程序#xff0c;我们需要了解系统调用耗费时间的方面#xff0c;同时学会系统调用的错误处理机制。 本文来源#xff1a;http://blog.csdn.net/trochiluses/article/details/11103523 #includestdio.h
#inc…摘要linux中cp命令的实现通过这个程序我们需要了解系统调用耗费时间的方面同时学会系统调用的错误处理机制。 本文来源http://blog.csdn.net/trochiluses/article/details/11103523 #includestdio.h
#includeunistd.h
#includestdlib.h
#includefcntl.h#define BUFFERSIZE 4096
#define COPYMODE 644void oops(char *,char *);
int main(int argc, char *argv[])
{int in_fd,out_fd,n_chars;char buf[BUFFERSIZE];if((in_fdopen(argv[1],O_RDONLY))-1)oops(cant open ,argv[1]);if ((out_fdcreat(argv[2],COPYMODE))-1){oops(cannot creat,argv[2]);}while((n_charsread(in_fd,buf,BUFFERSIZE))0){if((write(out_fd,buf,n_chars))!n_chars){oops(write error to,argv[2]);}}if(n_chars-1)oops(read err from,argv[1]);if(close(in_fd)-1||close(out_fd)-1)oops(fail to close,);return 0;
}void oops(char *s1,char *s2)
{fprintf(stderr,Error : %s,s1);perror(s2);exit(1);
}注意 1关于系统调用 read和write属于初级读写函数也是系统调用系统调用需要消耗大量时间。因为代码执行权会从用户转移到内核执行内核代码是需要时间的。系统调用开销巨大因为系统调用需要特殊的内存和堆栈环境这些需要在系统调用之前建立好系统调用之后又需要恢复这些环境。这种环境切换需要耗费大量时间。最好的方法就是建立缓冲区一次读取大量数据避免多次进行系统调用。我们可以用这个思想来改造前一篇中的who。 2系统调用的错误处理 一般约定系统调用openwritelseek在出错时会返回值-1。另外系统调用都有自己的错误集以open为例打开文件不存在没有读的权限打开文件太多等等。内核通过全局变量errno来确定错误类型其中哦功能error.h中规定了一些错误的宏。 a。可以根据errno来分别进行错误处理 #includeerror.h
extern int errno;int sample()
{int fd; fdopen(file,O_RDONLY);if(fd-1){printf(can not open file:);if(error ENOENT)printf(there is no such file);if (errorINTR){ printf(interrupted while opening file);} ... }
}b.显示错误信息 可以利用perror来通过error来寻找错误信息。 #includeerror.h
extern int errno;int sample()
{int fd; fdopen(file,O_RDONLY);if(fd-1){perror(can not open file:);}
}