出错处理APUE-1.7

    xiaoxiao2021-03-25  67

    当UNIX系统函数出错时,通常返回一个负值,而且整型变量errno通常被设置为具有特定信息的值。 文件 < errno.h >中定义了errno以及可以与它的各种常量。这些常量都以字符E开头。 POSIX 和 ISO C 将 errno定义为一个符号, 它扩展成为一个可以修改的整形左值(lvalue). 以前它的定义是: extern int errno; 但是在支持多线程的环境中,多个线程共享进程空间,每个线程都有属于它自己的局部errno以避免一个线程干扰另一个线程。例如Linux支持多线程存取errno,将其定义为 extern int *__errno_location(void); #define errno (*__errno_location())

    对于errno有两条规则: 第一:如果没有出错,其值不会被例程清除。 第二:任何函数都不会将errno值设置为0, 而且在 < errno.h >中定义的所有常量都不为 0

    C标准定义了两个函数,它们用于打印出错信息。

    #include <string.h> char *strerror(int errnum);

    strerror 函数将 errnum (通常就是 errno 值)映射为一个出错的消息字符串,并且返回此字符串的指针。

    #include <stdio.h> void perror(const char *msg);

    perror 函数基于errno的当前值,在标准错误上产生一条出错消息,然后返回。

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main(int argc, char *argv[]) { fprintf(stderr, "EACCES: %s\n", strerror(EACCES)); errno = ENOENT; perror(argv[0]); exit(0); }

    运行结果如下图:

    转载请注明原文地址: https://ju.6miu.com/read-34857.html

    最新回复(0)