1 perror 定義在頭文件<stdlib.h>中
void perror(const char *s);
函數說明
perror ( )用 來 將 上 一 個 函 數 發 生 錯 誤 的 原 因 輸 出 到 標 准 設備 (stderr) 。參數 s 所指的字符串會先打印出,后面再加上錯誤原因字符串。此錯誤原因依照全局變量errno 的值來決定要輸出的字符串。 在庫函數中有個errno變量,每個errno值對應着以字符串表示的錯誤類型。當你調用"某些"函數出錯時,該函數已經重新設置了errno的值。perror函數只是將你輸入的一些信息和現在的errno所對應的錯誤一起輸出。
2 errno 定義在頭文件#include <errno.h>
errno是一個全局變量,這里使用不同的數值代表不同場景下出錯的原因,當調用linux 系統api 失敗時,這時可以根據errno知道失敗的大致原因。
在程序代碼中包含errno.h ,然后每次程序調用失敗時系統會自動用用錯誤代碼填充errno,使用方法見下方:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <errno.h>
#define PAGE_SIZE 4096
#define TEST_FILE "/dev/mymap"
int main(int argc , char *argv[])
{
int fd;
int i;
unsigned char *p_map;
//打開設備
fd = open(TEST_FILE,O_RDWR);
if(fd < 0)
{
perror("TEST_FILE");
printf("errno=%d\n",errno);
char * mesg = strerror(errno);
printf("Mesg:%s\n",mesg);
exit(1);
}
//內存映射
p_map = (unsigned char *)mmap(0, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,fd, 0);
if(p_map == MAP_FAILED)
{
printf("mmap fail\n");
goto here;
}
//打印映射后的內存中的前10個字節內容
for(i=0;i<50;i++)
printf("%d\n",p_map[i]);
here:
munmap(p_map, PAGE_SIZE);
return 0;
}
調用執行結果

