cp下令的编写——浅谈系统调用

cp命令的编写——浅谈系统调用

摘要:linux中cp命令的实现,通过这个程序,我们需要了解系统调用耗费时间的方面,同时学会系统调用的错误处理机制。


本文来源:http://blog.csdn.net/trochiluses/article/details/11103523

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>

#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<error.h>
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<error.h>
extern int errno;

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




1楼trochiluses前天 15:19
这里还有一个问题没有解决;终端编程,终端是一个设备,对设备的读写同对文件的读写,但是在从一个终端读到另外一个终端的时候,出现了一些问题