20145234黄斐《信息安全系统设计基础》第十周

教材内容概述

解决错误检查问题:使用错误处理包装函数

Unix系统中的错误处理

Unix风格的错误处理

fork、wait等的早期函数的返回值既包括错误代码也包括有用的结果

if((pid=wait(NULL))<0)

{

  fprintf(stderr,"wait error: %s\n",strerror(errno));

  exit(0);

}

Posix风格的错误处理

许多较新的Posix函数,只能用返回值来表明成功(0)或失败(非0)。任何有用的结果都返回在通过引用传递进来的函数参数中。

if((retcode=pthread_create(&tid,NULL,thread,NULL))!=0)

{ 

  fprintf(stderr,"pthread_create error: %s\n",

        strerror(retcode));

  exit(0);

}

DNS风格的错误处理

gethostbyname和gethostbyname函数检索DNS(域名系统)主机条目,它们有另外一种返回错误的方法。这些函数在失败时返回NULL指针,并设置全局变量h_errno。

if((p=gethostbyname(name))==NULL)

{

  fprintf(stderr,"gethostbyname error: %s\n:",

         hstrerror(h_errno));

  exit(0);

}

错误处理包装函数

Unix风格的错误处理包装函数

kill函数

void Kill(pid_t pid,int signum)

{

  int tc;

  if((rc=kill(pid,signum))<0)

    unix_error("Kill error");

}

wait函数

pid_t Wait(int *status)

{

  pid_t pid;

  if((pid=wait(status))<0)

    unix_error("Wait error");

  return pid;

}

Poisx风格的错误处理包装函数

void Pthread_detach(pthread_t tid)

{

  int rc;

  if((rc=pthread_detach(tid))!=0)

    posix_error(rc,"Pthread_detach error");

}

DNS风格的错误处理包装函数

struct hostent *Gethostbyname(const char *name)

{

  struct hostent *p;

  if((p=gethostbyname(name))==NULL)

    dns_error("Gethostbyname error");

  return p;

}

posted @ 2016-11-17 22:21  20145234黄斐  阅读(180)  评论(0编辑  收藏  举报