當linux中的C api函數發生異常時,一般會將errno變數(需include
errno.h)賦一個整數值,不同的值表示不同的含義,可以通過查看該值推測出錯的原因,在實際編程中用這一招解決了不少原本看來莫名其妙的問題。但是errno是一個數字,代表的具體含義還要到errno.h中去閱讀宏定義,而每次查閱是一件很繁瑣的事情。有下面幾種方法可以方便的得到錯誤資訊
(1)void perror(const char *s)
函數說明
perror ( )用來將上一個函數發生錯誤的原因輸出到標準錯誤(stderr),參數s
所指的字串會先列印出,後面再加上錯誤原因 字串。此錯誤原因依照全域變數
errno 的值來決定要輸出的字串。
(2) char *strerror(int errno)
將錯誤碼轉換為字串錯誤資訊,可以將該字串和其它的資訊組合輸出到使用者介面例如
fprintf(stderr,"error in CreateProcess %s, Process ID %d
",strerror(errno),processID)
註:假設processID是一個已經擷取了的整形ID
(3)printf("%m", errno);
另外不是所有的地方發生錯誤的時候都可以通過error擷取錯誤碼,例如下面的程式碼片段
#include"stdio.h"
#include "stdlib.h"
#include "errno.h"
#include "netdb.h"
#include "sys/types.h"
#include "netinet/in.h"
int main (int argc, char *argv[])
{
struct hostent *h;
if (argc != 2)
{
fprintf (stderr ,"usage: getip address\n");
exit(1);
}
if((h=gethostbyname(argv[1])) == NULL)
{
herror("gethostbyname");
exit(1);
}
printf("Host name : %s\n", h->h_name);
printf("IP Address : %s\n", inet_ntoa (*((struct in_addr *)h->h_addr)));
return 0;
}
通過上面的代碼可以看到:使用gethostbyname()函數,你不能使用perror()來輸出錯誤資訊(因為錯誤碼儲存在
h_errno 中而不是errno 中。所以,你需要調用herror()函數。
你簡單的傳給gethostbyname()
一個機器名("bbs.tsinghua.edu.cn"),然後就從返回的結構struct hostent
中得到了IP 等其他資訊.程式中輸出IP 位址的程式需要解釋一下:h->h_addr
是一個char*,但是inet_ntoa()函數需要傳遞的是一個struct in_addr
結構。所以上面將h->h_addr 強制轉換為struct
in_addr*,然後通過它得到了所有資料。