Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux errno 錯誤代碼基礎教學與查詢技巧

編輯:Linux 教學

errno 基本概念

當 Linux C API 函式發生錯誤時,會將全域變數 errno(需 #include <errno.h>)設為特定整數值,不同值代表不同錯誤原因。透過檢查 errno 可快速定位問題。

常用錯誤輸出函式

函式用途範例
perror(const char *s)將上一個函式的錯誤原因輸出到 stderr,前綴字串 sperror("open failed");
strerror(int errno)將錯誤代碼轉為描述字串,可組合輸出fprintf(stderr, "Error: %s", strerror(errno));
printf("%m")格式化字串直接輸出 errno 對應錯誤訊息printf("Error: %m\n", errno);

特殊情況:h_errno

網路相關函式(如 gethostbyname())錯誤代碼存放在 h_errno 而非 errno,需使用 herror() 輸出。

常見 errno 代碼對照表(節錄)

代碼宏定義含義
1EPERM操作不被允許
2ENOENT檔案或目錄不存在
13EACCES權限被拒絕
11EAGAIN資源暫時不可用,請重試
12ENOMEM記憶體不足
28ENOSPC裝置剩餘空間不足
32EPIPE管道破裂
111ECONNREFUSED連線被拒絕

查詢技巧

  • 終端機輸入 errno 13 即可顯示代碼 13 對應資訊(需安裝 errno 套件)。
  • 查閱 /usr/include/asm-generic/errno-base.h 及 errno.h 完整定義。
  • 程式中善用 strerror() 將錯誤碼轉為人類可讀訊息記錄日誌。
Copyright © Windows教程網 All Rights Reserved