Linux C/C++ 系统错误

在C++中,如果调用了库函数,可以通过函数的返回值判断调用是否成功。其实还有一个整型的全局变量errno,存放了函数调用过程中产生的错误代码。

如果调用库函数失败,可以通过errno的值来查找原因

复制代码
#include <errno.h>

strerror()库函数(在<string.h>中声明)

复制代码
char *strerror(int errnum);		//非线程安全
int strerror_r(int errnum,char *buf,size_t buflen);		//线程安全

gcc8.3.1版本一共有133个错误代码

举例

复制代码
#include<iostream>
#include<string.h>
#include<errno.h>
#include<sys/stat.h>
using namespace std;

int main()
{
    int iret = mkdir("/tmp/aaa",0755);

    cout<<"iret="<<iret<<endl;
    cout<<"error="<<strerror(errno)<<endl;
}

[root@localhost 06demoerror]# g++ -o demo_error demo_error.cpp 
[root@localhost 06demoerror]# ./demo_error 
iret=0
error=Success
[root@localhost 06demoerror]# ./demo_error 
iret=-1
error=File exists

perror()库函数

在<stdio.h>中声明,用于在控制台显示最近一次系统错误消息

复制代码
void perror(const char*s);

调用库函数不一定设置errno,errno不能作为调用库函数失败的标准


推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt

相关推荐
..过云雨8 小时前
05.【Linux系统编程】进程(冯诺依曼体系结构、进程概念、进程状态(注意僵尸和孤儿)、进程优先级、进程切换和调度)
linux·笔记·学习
Gu_shiwww9 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
matlab的学徒9 小时前
Web与Nginx网站服务(改)
linux·运维·前端·nginx·tomcat
Insist7539 小时前
prometheus安装部署与alertmanager邮箱告警
linux·运维·grafana·prometheus
你怎么知道我是队长9 小时前
C语言---循环结构
c语言·开发语言·算法
BAGAE9 小时前
MODBUS 通信协议详细介绍
linux·嵌入式硬件·物联网·硬件架构·iot·嵌入式实时数据库·rtdbs
灿烂阳光g9 小时前
SELinux 策略文件编写
android·linux
xqlily9 小时前
Linux操作系统之Ubuntu
linux·运维·ubuntu
老赵的博客10 小时前
c++ unqiue指针
java·jvm·c++
阿部多瑞 ABU10 小时前
《基于国产Linux的机房终端安全重构方案》
linux·安全