【Linux Error处理】

 在调用标准库函数时,通常会对返回值进行处理。比如:fopen,malloc,socket等,普遍的处理办法时,返回错误时

printf("open xxx error");

retun -1;

...

 这样的报错,我们仅仅知道打开文件失败了,具体原因却无从知晓,只能跟踪调试了。如果,使用error函数来处理,

我们就可以得直接错误信息。

#include<stdio.h>
#define NDEBUG
#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<error.h>
#include<errno.h>

int main(int argc, char *argv[])
{
        int fd[2];

        if (pipe(fd)<0)
                error(errno,errno,"[%s,%s,%d]",__FILE__,__func__,__LINE__);

        if (fopen("xxx","r") == NULL)
                error(errno,errno,"[%s,%s,%d]",__FILE__,__func__,__LINE__);

        return 0;
}

当error第一个参数填0时,程序不会退出,非0时,退出,第2个参数为库函数的错误返回码,不同的错误码对应着不同的情况,能帮助我们更快的定位问题。如把文件xxx的权限修改为0,则会报错:./a.out: [main.c,main,29]: Permission denied。

错误码可以在文件./include/linux/errno.h中进行查看。




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值