APUE——unix出錯處理

1. errno原理

當UNIX函數出錯時(系統調用),常常會返回一個負值,而且整型變量errno通常被設置爲含有附加信息的一個值。

文件<errno.h>中定義了符合errno以及可以賦予它的各種常量,這些常量都以字符E開頭。另外,UNIX系統手冊第2部分的第1頁intro(2)列出了所有這些出錯常量。在Linux中,出錯常量在errno(3)手冊頁中列出(可以使用命令man 3 errno查看)。

  1. errno被重新定義爲線程私有數據。這樣,一個線程做了設置errno的操作並不會影響進程中其他線程的errno的值。
  2. 如果沒有出錯,則其值不會被一個例程清除。因此,僅當函數的返回值指明出錯時,才檢驗其值。
  3. 任一函數都不會將errno值設置爲0,在<errno.h>中定義的所有常量都不爲0。
extern int errno;

將errno設置爲線程局部變量是個不錯的主意,事實上,GCC中就是這麼幹的。他保證了線程之間的錯誤原因不會互相串改,當你在一個線程中串行執行一系列過程,那麼得到的errno仍然是正確的。
多線程的時候,爲了保證線程安全,在單個線程中,errno通過指針獲取當前線程中的錯誤信息

extern int *__errno_location(void);
#define errno (*__errno_locatioin())

2. errno的獲取函數

2.1 strerror

輸入爲errno的整形值,爲errno或者是具體的枚舉的key

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

int main ()
{
   FILE *fp;

   fp = fopen("file.txt","r");
   if( fp == NULL ) 
   {
      printf("Error: %s\n", strerror(errno));
   }
   
  return(0);
}
Error: No such file or directory

2.2 perror

C 庫函數 void perror(const char *str) 把一個描述性錯誤消息輸出到標準錯誤 stderr。首先輸出字符串 str,後跟一個冒號,然後是一個空格。

void perror(const char *str)

#include <pthread.h>
#include "apue.h"
#include <errno.h>

int main()
{
    FILE* fp;

    fp = fopen("filename.txt","r");
    if(fp == NULL)
        perror("Error: ");
    printf("the error is : %s\n",strerror(errno));
    for(int i = 0;i<=256;i++)
        printf("errno: %2d\t%s\n",i,strerror(i));
	return 0;
}
Error: : No such file or directory
the error is : No such file or directory
errno:  0       Success
errno:  1       Operation not permitted
errno:  2       No such file or directory
errno:  3       No such process
errno:  4       Interrupted system call
errno:  5       Input/output error
errno:  6       No such device or address
errno:  7       Argument list too long
errno:  8       Exec format error
errno:  9       Bad file descriptor
errno: 10       No child processes
等133
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章