Chinaunix首页 | 论坛 | 博客
  • 博客访问: 267215
  • 博文数量: 113
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1044
  • 用 户 组: 普通用户
  • 注册时间: 2015-02-15 16:09
文章分类

全部博文(113)

文章存档

2016年(5)

2015年(108)

我的朋友

分类: C/C++

2015-10-22 19:43:59

错误处理的三种方法

点击(此处)折叠或打开

  1. /* 错误处理过程 */
  2. #include<stdio.h>
  3. #include<errno.h>
  4. #include <arpa/inet.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include<pthread.h>
  8. /* 检测错误是保证健壮性的必要手段 */
  9. void thread(){
  10.     printf("false.\n");
  11. }
  12. int main(){
  13.     int sock;
  14.     sock = socket(PF_INET, SOCK_STREAM, 0);
  15.     /* 方法一 全局变量errno标识错误代码*/
  16.     if(sock<0){
  17.         fprintf(stderr,"wait error:%s\n",strerror(errno));
  18.         exit(0);
  19.     }
  20.     int tid;
  21.     int retcode;
  22.     /* 方法二
  23.     结构retcode 标识错误代码 */
  24.     if((retcode=pthread_create(&tid,NULL,thread,NULL))!=0){
  25.         fprintf(stderr,"pthread_create error:%s\n",strerror(retcode));
  26.     }
  27.     /* 方法三
  28.     网络编程,若函数调用失败,则返回NULL,并设置全局变量h_errno,通过strerror(h_errno)输出错误原因*/
  29.     if((p=gethostbyname(name))!=NULL){
  30.         fprintf(stderr,"gethostbyname error:%s\n",strerror(h_errno));
  31.         exit(0);
  32.     }
  33.     printf("OK!\n");
  34.     return 0;
  35. }

阅读(1475) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~