1. 程式人生 > >[Linux]出錯處理errno

[Linux]出錯處理errno

linux linux系統 當前 部分函數 mar int 避免 線程 依然

概述

公共頭文件<errno.h>定義了一個整型值errno以及可以賦予它的各種常量。

大部分函數出錯後返回-1,並且自動給errno賦予當前發生的錯誤枚舉值。

需要註意的一點是,errno只有在錯誤發生時才會被復寫,這就意味著如果按順序執行AB兩個函數,如果只有A函數出錯,則執行完AB函數後errno依然保留著A函數出錯的枚舉值,

如果AB均出錯,那麽在B之前如果errno沒有被處理,那麽將會被B出錯的枚舉值所覆蓋。

Linux

為了避免多線程環境共享一個errno,Linux系統定義了一個宏來解決這個問題

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

示例

#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

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

char buf[500000];

int main(void)
{
    int re, my_errno;

    re = read(90
, buf, sizeof(buf)); if(re > -1){ my_errno = 0; }else{ my_errno = errno; perror("file error"); } printf("%d\n", my_errno); re = 0; re = open("./not_exists_file", O_RDONLY); if(re > -1){ my_errno = 0; }else{ my_errno
= errno; perror("file error"); } printf("%d\n", my_errno); return 0; }

以上代碼輸出:

file error: Bad file descriptor
9
file error: No such file or directory
2

[Linux]出錯處理errno