Linux环境错误处理方式

Linux系统的系统调用通过设置全局errno来标示错误类型http://blog.chinaunix.net/u2/87570/showart_2137607.html,并通过perrorsperror函数提供对errno的解析。

 

而我们平时写程序的错误处理方式类似于下面的代码:

if ( p == NULL ){
  printf ( "ERR: The pointer is NULL\n" );
}

if(socket(PF_INET, SOCK_STREAM, 0) < 0) {
    printf(“create socket errr\n”);
}

 

这种方式虽然没什么问题,但其对相同的问题缺乏共性的处理,错误处理应以统一的形式进行处理,那么该如何实现诸如errno错误处理的方式呢?

 

/* 声明出错代码 */
#define   ERR_NO_ERROR  0 /* No error         */
#define   ERR_OPEN_FILE  1 /* Open file error     */
#define   ERR_SEND_MESG  2 /* sending a message error */
#define   ERR_BAD_ARGS  3 /* Bad arguments      */
#define   ERR_MEM_NONE  4 /* Memeroy is not enough  */
#define   ERR_SERV_DOWN  5 /* Service down try later  */

/* 声明出错信息 */
char* errmsg[] = {
  /* 0 */    "No error",        
  /* 1 */    "Open file error",    
  /* 2 */    "Failed in sending/receiving a message", 
  /* 3 */    "Bad arguments", 
  /* 4 */    "Memeroy is not enough",
  /* 5 */    "Service is down; try later",
};

/* 声明错误代码全局变量 */
long errno = 0;
  
/* 打印出错信息函数 */
void perror( char* info)
{
  if ( info ){
      printf("%s: %s\n", info, errmsg[errno] );
    return;
   } 
   printf("Error: %s\n", errmsg[errno] );
}

/* 这个基本上是ANSI的错误处理实现细节了,当你程序中有错误时你就可以这样处理 */
bool CheckPermission( char* userName )
{
  if ( strcpy(userName, "root") != 0 ){
    errno = ERR_PERMISSION_DENIED;
    return (FALSE);
   }
    …
}
  
int main()
{
    ...
    if (! CheckPermission( username ) ){
      perror("main()");
    }
    ...
}

 

 
 

 

 
posted @ 2013-04-19 14:07  ydzhang  阅读(176)  评论(0编辑  收藏  举报