设为首页 加入收藏

TOP

cp命令的编写――浅谈系统调用
2014-11-23 21:54:15 来源: 作者: 【 】 浏览:3
Tags:命令 编写 系统 调用
#include
#include
#include
#include

#define BUFFERSIZE 4096
#define COPYMODE 644

void oops(char *,char *);
int main(int argc, char *argv[])
{
  int in_fd,out_fd,n_chars;
  char buf[BUFFERSIZE];

  if((in_fd=open(argv[1],O_RDONLY))==-1)
    oops("can't open ",argv[1]);
  if ((out_fd=creat(argv[2],COPYMODE))==-1)
  {
    oops("cannot creat",argv[2]);
  }
  while((n_chars=read(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)系统调用的错误处理
一般约定,系统调用open,write,lseek在出错时会返回值-1。另外,系统调用都有自己的错误集,以open为例,打开文件不存在,没有读的权限,打开文件太多等等。内核通过全局变量errno来确定错误类型,其中哦功能error.h中规定了一些错误的宏。
a。可以根据errno来分别进行错误处理:
#include
extern int errno;

int sample()
{
  int fd; 
  fd=open("file",O_RDONLY);
  if(fd==-1)
  {
      printf("can not open file:");

      if(error== ENOENT)
        printf("there is no such file");
      if (error==INTR)
      {   
        printf("interrupted while opening file");
      }   
      ... 
  }
}

b.显示错误信息:
可以利用perror来通过error来寻找错误信息。
#include
extern int errno;

int sample()
{
  int fd; 
  fd=open("file",O_RDONLY);
  if(fd==-1)
  {
    perror("can not open file:");
  }
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UVA 10718 Bit Mask 贪心+位运算 下一篇[LeetCode] Implement strstr() t..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis压力测试实战 - (2025-12-27 09:20:24)
·高并发一上来,微服 (2025-12-27 09:20:21)
·Redis 高可用架构深 (2025-12-27 09:20:18)
·Linux 系统监控 的完 (2025-12-27 08:52:29)
·一口气总结,25 个 L (2025-12-27 08:52:27)