Errno коды ошибок linux

# @see /usr/include/asm-generic/errno-base.h #ifndef _ASM_GENERIC_ERRNO_BASE_H #define _ASM_GENERIC_ERRNO_BASE_H #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */ #endif # @see /usr/include/asm-generic/errno.h #ifndef _ASM_GENERIC_ERRNO_H #define _ASM_GENERIC_ERRNO_H #include <asm-generic/errno-base.h> #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale NFS file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ECANCELED 125 /* Operation Canceled */ #define ENOKEY 126 /* Required key not available */ #define EKEYEXPIRED 127 /* Key has expired */ #define EKEYREVOKED 128 /* Key has been revoked */ #define EKEYREJECTED 129 /* Key was rejected by service */ /* for robust mutexes */ #define EOWNERDEAD 130 /* Owner died */ #define ENOTRECOVERABLE 131 /* State not recoverable */ #define ERFKILL 132 /* Operation not possible due to RF-kill */ #endif
errno(3) Library Functions Manual errno(3)

ИМЯ

errno — код
последней
ошибки

LIBRARY

Standard C library (libc, -lc)

СИНТАКСИС

#include <errno.h>

ОПИСАНИЕ

В
заголовочном
файле <errno.h>
определяется
целочисленная
переменная
errno, которая
используется
системными
вызовами и
некоторыми
библиотечными
функциями
при
ошибках
для
указания
того, что
именно
произошло.

Значение
errno имеет
смысл
только
тогда,
когда
вызов
возвратил
ошибку (а
именно: -1 —
для
большинства
системных
вызовов; NULL —
для
большинства
библиотечных
функций);
при
успешном
выполнении
функции
также
могут
менять
значение
errno.
Системные
вызовы и
библиотечные
функции
никогда не
присваивают
errno
значение
нуля.

Некоторые
системные
вызовы или
библиотечные
функции
(например,
getpriority(2)), при
успешном
выполнении
возвращают
-1. В этих
случаях
успешность
выполнения
можно
отличить
от ошибки
присвоив
errno
значение
нуля перед
вызовом, и
затем, если
вызов
вернул
состояние,
которое
может
указывать
на ошибку,
проверить,
равно ли errno
ненулевому
значению.

Переменная
errno
определена
в
стандарте ISO
C как
изменяемое
lvalue int и не
объявляемая
явно; errno
может быть
и макросом.
Переменная
errno
является
локальным
значением
нити; её
изменение
в одной
нити не
влияет на
её
значение в
другой
нити.

Номера и
имена
ошибок

Все
положительные
числа
считаются
допустимыми
номерами
ошибок. В
заголовочном
файле <errno.h>
определены
символические
имена для
каждого
номера
возможной
ошибки,
который
может
появиться
в errno.

Всем
названиям
ошибок,
определённым
в POSIX.1, должны
соответствовать
разные
значения,
за
исключением
EAGAIN и EWOULDBLOCK,
которые
могут быть
одинаковыми.
В Linux эти они
имеют
одинаковое
значение
на всех
архитектурах.

В разных
системах UNIX
символическим
именам
ошибок
назначены
разные
номера, и
это верно
даже в Linux для
разных
архитектур.
Поэтому
числовые
значение
не указаны
в
представленном
далее
списке
имён
ошибок. Для
преобразования
этих имён в
текстовые
сообщения
об ошибках
можно
использовать
функции perror(3)
и strerror(3).

В любой
системе Linux
можно
получить
список
всех
символических
имён
ошибок и
соответствующие
им номера с
помощью
команды errno(1))
(является
частью
пакета moreutils):

$ errno -l
EPERM 1 Операция не позволена
ENOENT 2 Нет такого файла или каталога
ESRCH 3 Нет такого процесса
EINTR 4 Прерван системный вызов
EIO 5 Ошибка ввода/вывода
...

Команду
errno(1) также
можно
использовать
для поиска
ошибок по
имени или
номеру, а
также по
строке,
входящей в
описание
ошибки:

$ errno 2
ENOENT 2 Нет такого файла или каталога
$ errno ESRCH
ESRCH 3 Нет такого процесса
$ errno -s permission
EACCES 13 Отказано в доступе

Список
имён
ошибок

В
представленном
далее
списки
символических
имён
ошибок у
некоторых
есть
некоторые
примечания:

POSIX.1-2001
The name is defined by POSIX.1-2001, and is defined in later POSIX.1
versions, unless otherwise indicated.
POSIX.1-2008
The name is defined in POSIX.1-2008, but was not present in earlier
POSIX.1 standards.
C99
The name is defined by C99.

Below is a list of the symbolic error names that are defined on
Linux:

E2BIG
Слишком
длинный
список
параметров
(POSIX.1-2001).
EACCES
Доступ
запрещён
(POSIX.1-2001).
EADDRINUSE
Адрес уже
используется
(POSIX.1-2001).
EADDRNOTAVAIL
Адрес
недоступен
(POSIX.1-2001).
EAFNOSUPPORT
Семейство
адресов не
поддерживается
(POSIX.1-2001).
EAGAIN
Ресурс
временно
недоступен
(значение
может быть
равным EWOULDBLOCK)
(POSIX.1-2001).
EALREADY
Соединение
уже
выполняется
(POSIX.1-2001).
EBADE
Некорректный
обмен.
EBADF
Неправильный
дескриптор
файла (POSIX.1-2001).
EBADFD
Некорректное
состояние
дескриптора
файла.
EBADMSG
Неправильное
сообщение
(POSIX.1-2001).
EBADR
Неверный
дескриптор
запроса.
EBADRQC
Неверный
код
запроса.
EBADSLT
Некорректный
слот.
EBUSY
Устройство
или ресурс
заняты (POSIX.1-2001).
ECANCELED
Операция
отменена
(POSIX.1-2001).
ECHILD
Отсутствуют
дочерние
процессы
(POSIX.1-2001).
ECHRNG
Номер
канала вне
диапазона.
ECOMM
Ошибка
связи при
отправке.
ECONNABORTED
Соединение
было
прервано
(POSIX.1-2001).
ECONNREFUSED
В
соединении
отказано
(POSIX.1-2001).
ECONNRESET
Соединение
сброшено
другой
стороной
(POSIX.1-2001).
EDEADLK
Предотвращена
тупиковая
ситуация
при
обращении
к ресурсу
(POSIX.1-2001).
EDEADLOCK
На
большинстве
архитектур
является
синонимом
EDEADLK. На
некоторых
архитектурах
(например, Linux
MIPS, PowerPC, SPARC), это
отдельный
код ошибки
«Ошибка
перекрёстной
блокировки
файла».
EDESTADDRREQ
Требуется
указать
адрес
назначения
(POSIX.1-2001).
EDOM
Математический
аргумент
вне
области
определения
функции (POSIX.1,
C99).
EDQUOT
Превышена
дисковая
квота (POSIX.1-2001).
EEXIST
Файл
существует
(POSIX.1-2001).
EFAULT
Неправильный
адрес (POSIX.1-2001).
EFBIG
Файл
слишком
велик (POSIX.1-2001).
EHOSTDOWN
Узел
выключен.
EHOSTUNREACH
Узел
недоступен
(POSIX.1-2001).
EHWPOISON
В странице
памяти
аппаратная
ошибка.
EIDRM
Идентификатор
удалён (POSIX.1-2001).
EILSEQ
Неверный
или
неполный
мультибайтный
или
широкий
символ (POSIX.1, C99).
Этот текст
взят из
описания
ошибки glibc; в POSIX.1
эта ошибка
звучит как
«Недопустимая
последовательность
байт».
EINPROGRESS
Операция
выполняется
(POSIX.1-2001).
EINTR
Прерванный
вызов
функции (POSIX.1-2001);
смотрите
signal(7).
EINVAL
Неверный
аргумент
(POSIX.1-2001).
EIO
Ошибка
ввода/вывода
(POSIX.1-2001).
EISCONN
Сокет
подключён
(POSIX.1-2001).
EISDIR
Это
каталог
(POSIX.1-2001).
EISNAM
Является
файлом
именованного
типа.
EKEYEXPIRED
Ключ с
истёкшим
сроком.
EKEYREJECTED
Ключ был
отвергнут
службой.
EKEYREVOKED
Ключ был
отозван.
EL2HLT
Уровень 2
остановлен.
EL2NSYNC
Уровень 2
не
синхронизирован.
EL3HLT
Уровень 3
остановлен.
EL3RST
Уровень 3
сброшен.
ELIBACC
Невозможно
получить
доступ к
нужной
общей
библиотеке.
ELIBBAD
Обращение
к
повреждённой
общей
библиотеке.
ELIBMAX
Попытка
компоновки
с слишком
большим
количеством
общих
библиотек.
ELIBSCN
Секция .lib в a.out
повреждена
ELIBEXEC
Невозможно
непосредственно
выполнить
общую
библиотеку.
ELNRNG
Число
ссылок вне
допустимого
диапазона.
ELOOP
Слишком
много
уровней
символьных
ссылок (POSIX.1-2001).
EMEDIUMTYPE
Неправильный
тип
носителя.
EMFILE
Too many open files (POSIX.1-2001). Commonly caused by exceeding the
RLIMIT_NOFILE resource limit described in getrlimit(2). Can
also be caused by exceeding the limit specified in
/proc/sys/fs/nr_open.
EMLINK
Слишком
много
ссылок (POSIX.1-2001).
EMSGSIZE
Сообщение
слишком
длинное
(POSIX.1-2001).
EMULTIHOP
Попытка Multihop
(POSIX.1-2001).
ENAMETOOLONG
Слишком
длинное
название
файла (POSIX.1-2001).
ENETDOWN
Сеть не
работает
(POSIX.1-2001).
ENETRESET
Соединение
прервано
из-за сети
(POSIX.1-2001).
ENETUNREACH
Сеть
недоступна
(POSIX.1-2001).
ENFILE
Слишком
много
открытых
файлов в
системе (POSIX.1-2001).
В Linux это,
вероятно,
результат
достижения
ограничения
/proc/sys/fs/file-max
(смотрите
proc(5)).
ENOANO
Не anode.
ENOBUFS
Недостаточно
буферного
пространства
(POSIX.1 (часть XSI STREAMS)).
ENODATA
The named attribute does not exist, or the process has no access to this
attribute; see xattr(7).
In POSIX.1-2001 (XSI STREAMS option), this error was described as «No
message is available on the STREAM head read queue».
ENODEV
Нет такого
устройства
(POSIX.1-2001).
ENOENT
Нет такого
файла или
каталога
(POSIX.1-2001).
Обычно, эта
ошибка
является
результатом
указания
несуществующего
пути или
отсутствия
одного из
компонентов
каталогов
пути, или
указанный
путь
является
символической
ссылкой на
несуществующий
объект.
ENOEXEC
Ошибка
формата
выполняемого
файла (POSIX.1-2001).
ENOKEY
Требуемый
ключ
недоступен.
ENOLCK
Нет
доступных
блокировок
(POSIX.1-2001).
ENOLINK
Соединение
было
разорвано
(POSIX.1-2001).
ENOMEDIUM
Носитель
не найден.
ENOMEM
Недостаточно
места/невозможно
выделить
память (POSIX.1-2001).
ENOMSG
Нет
сообщения
желаемого
типа (POSIX.1-2001).
ENONET
Машина не в
сети.
ENOPKG
Пакет не
установлен.
ENOPROTOOPT
Протокол
недоступен
(POSIX.1-2001).
ENOSPC
На
устройстве
не
осталось
места (POSIX.1-2001).
ENOSR
Отсутствую
ресурсы STREAM (POSIX.1
(часть XSI STREAMS)).
ENOSTR
Нет STREAM (POSIX.1
(часть XSI STREAMS)).
ENOSYS
Функция не
реализована
(POSIX.1-2001).
ENOTBLK
Требуется
блочное
устройство.
ENOTCONN
Сокет не
подключён
(POSIX.1-2001).
ENOTDIR
Не каталог
(POSIX.1-2001).
ENOTEMPTY
Каталог не
пуст (POSIX.1-2001).
ENOTRECOVERABLE
Состояние
нельзя
восстановить
(POSIX.1-2008).
ENOTSOCK
Не сокет
(POSIX.1-2001).
ENOTSUP
Операция
не
поддерживается
(POSIX.1-2001).
ENOTTY
Неподходящая
операция
управления
вводом/выводом
(POSIX.1-2001).
ENOTUNIQ
Имя не
уникально
в сети.
ENXIO
Нет такого
устройства
или адреса
(POSIX.1-2001).
EOPNOTSUPP
Операция
не
поддерживается
на сокете
(POSIX.1-2001).
(ENOTSUP и EOPNOTSUPP в Linux
имеют
одинаковые
значения,
но
согласно POSIX.1
значения
этих
ошибок
должны
различаться.)
EOVERFLOW
Значение
слишком
велико для
хранения в
таком типе
данных (POSIX.1-2001).
EOWNERDEAD
Владелец
умер (POSIX.1-2008).
EPERM
Операция
не
позволена
(POSIX.1-2001).
EPFNOSUPPORT
Семейство
протоколов
не
поддерживается.
EPIPE
Обрыв
канала (POSIX.1-2001).
EPROTO
Ошибка
протокола
(POSIX.1-2001).
EPROTONOSUPPORT
Протокол
не
поддерживается
(POSIX.1-2001).
EPROTOTYPE
Неверный
тип
протокола
для сокета
(POSIX.1-2001).
ERANGE
Результат
слишком
большой (POSIX.1,
C99).
EREMCHG
Удалённый
адрес был
изменён.
EREMOTE
Это
удалённый
объект.
EREMOTEIO
Ошибка
удалённого
ввода/вывода.
ERESTART
Прерванный
системный
вызов
следует
перезапустить.
ERFKILL
Операция
не
позволяется
из-за RF-kill.
EROFS
Файловая
система
доступна
только для
чтения (POSIX.1-2001).
ESHUTDOWN
Невозможно
отправить
данные
после
выключения
конечной
точки
передачи.
ESPIPE
Недопустимое
перемещение
(POSIX.1-2001).
ESOCKTNOSUPPORT
Тип сокета
не
поддерживается.
ESRCH
Нет такого
процесса
(POSIX.1-2001).
ESTALE
Неактуальный
дескриптор
файла (POSIX.1-2001).
Эта ошибка
может
возникать
в NFS и других
файловых
системах.
ESTRPIPE
Ошибка
потоков
канала.
ETIME
Таймер
истёк (POSIX.1
(часть XSI STREAMS)).
(в POSIX.1
описывается
как «в ioctl(2)
истекло
время
ожидания
STREAM»)
ETIMEDOUT
Время
ожидания
соединения
истекло
(POSIX.1-2001).
ETOOMANYREFS
Слишком
много
ссылок:
невозможно
объединить.
ETXTBSY
Текстовый
файл занят
(POSIX.1-2001).
EUCLEAN
Структуру
необходимо
очистить.
EUNATCH
Драйвер
протокола
не
подсоединён.
EUSERS
Слишком
много
пользователей.
EWOULDBLOCK
Операция
приведёт к
блокировке
(значение
может быть
равно EAGAIN)
(POSIX.1-2001).
EXDEV
Invalid cross-device link (POSIX.1-2001).
EXFULL
Обмен
полон.

ЗАМЕЧАНИЯ

Распространённая
ошибка:

if (somecall() == -1) {

printf("somecall() failedn");
if (errno == ...) { ... } }

Здесь errno
может
больше не
иметь
значение
результата
последнего
вызова somecall()
(т.е.,
значение
может
измениться
из-за printf(3)).
Если
значение
errno важно, то
его нужно
сохранять
между
библиотечными
вызовами:

if (somecall() == -1) {

int errsv = errno;
printf("somecall() failedn");
if (errsv == ...) { ... } }

Note that the POSIX threads APIs do not set errno on
error. Instead, on failure they return an error number as the function
result. These error numbers have the same meanings as the error numbers
returned in errno by other APIs.

В
некоторых
древних
системах
файл <errno.h>
отсутствовал
или не
объявлял
errno, поэтому
это нужно
было
делать
вручную
(например, extern
int errno
). Не
делайте
этого
. Это
давно уже
не нужно, и
вызовет
проблемы с
современными
версиями
библиотеки
C.

СМ. ТАКЖЕ

errno(1), err(3), error(3), perror(3),
strerror(3)

ПЕРЕВОД

Русский
перевод
этой
страницы
руководства
был сделан
Azamat Hackimov <azamat.hackimov@gmail.com>, Yuri Kozlov
<yuray@komyakino.ru> и Иван
Павлов
<pavia00@gmail.com>

Этот
перевод
является
бесплатной
документацией;
прочитайте
Стандартную
общественную
лицензию GNU
версии 3
или более
позднюю,
чтобы
узнать об
условиях
авторского
права. Мы не
несем
НИКАКОЙ
ОТВЕТСТВЕННОСТИ.

Если вы
обнаружите
ошибки в
переводе
этой
страницы
руководства,
пожалуйста,
отправьте
электронное
письмо на
man-pages-ru-talks@lists.sourceforge.net.

The errno command can do this. From man errno:

DESCRIPTION
       errno looks up errno macro names, errno codes, and the corresponding descriptions. For example, if given ENOENT on a Linux system, it prints
       out the code 2 and the description "No such file or directory".  If given the code 2, it prints ENOENT and the same description.

OPTIONS
       -l, --list
              List all errno values.

So, to see all of them, run:

$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 No such device or address
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EAGAIN 11 Resource temporarily unavailable
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Device or resource busy
EEXIST 17 File exists
EXDEV 18 Invalid cross-device link
ENODEV 19 No such device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Numerical result out of range
EDEADLK 35 Resource deadlock avoided
ENAMETOOLONG 36 File name too long
ENOLCK 37 No locks available
ENOSYS 38 Function not implemented
ENOTEMPTY 39 Directory not empty
ELOOP 40 Too many levels of symbolic links
EWOULDBLOCK 11 Resource temporarily unavailable
ENOMSG 42 No message of desired type
EIDRM 43 Identifier removed
ECHRNG 44 Channel number out of range
EL2NSYNC 45 Level 2 not synchronized
EL3HLT 46 Level 3 halted
EL3RST 47 Level 3 reset
ELNRNG 48 Link number out of range
EUNATCH 49 Protocol driver not attached
ENOCSI 50 No CSI structure available
EL2HLT 51 Level 2 halted
EBADE 52 Invalid exchange
EBADR 53 Invalid request descriptor
EXFULL 54 Exchange full
ENOANO 55 No anode
EBADRQC 56 Invalid request code
EBADSLT 57 Invalid slot
EDEADLOCK 35 Resource deadlock avoided
EBFONT 59 Bad font file format
ENOSTR 60 Device not a stream
ENODATA 61 No data available
ETIME 62 Timer expired
ENOSR 63 Out of streams resources
ENONET 64 Machine is not on the network
ENOPKG 65 Package not installed
EREMOTE 66 Object is remote
ENOLINK 67 Link has been severed
EADV 68 Advertise error
ESRMNT 69 Srmount error
ECOMM 70 Communication error on send
EPROTO 71 Protocol error
EMULTIHOP 72 Multihop attempted
EDOTDOT 73 RFS specific error
EBADMSG 74 Bad message
EOVERFLOW 75 Value too large for defined data type
ENOTUNIQ 76 Name not unique on network
EBADFD 77 File descriptor in bad state
EREMCHG 78 Remote address changed
ELIBACC 79 Can not access a needed shared library
ELIBBAD 80 Accessing a corrupted shared library
ELIBSCN 81 .lib section in a.out corrupted
ELIBMAX 82 Attempting to link in too many shared libraries
ELIBEXEC 83 Cannot exec a shared library directly
EILSEQ 84 Invalid or incomplete multibyte or wide character
ERESTART 85 Interrupted system call should be restarted
ESTRPIPE 86 Streams pipe error
EUSERS 87 Too many users
ENOTSOCK 88 Socket operation on non-socket
EDESTADDRREQ 89 Destination address required
EMSGSIZE 90 Message too long
EPROTOTYPE 91 Protocol wrong type for socket
ENOPROTOOPT 92 Protocol not available
EPROTONOSUPPORT 93 Protocol not supported
ESOCKTNOSUPPORT 94 Socket type not supported
EOPNOTSUPP 95 Operation not supported
EPFNOSUPPORT 96 Protocol family not supported
EAFNOSUPPORT 97 Address family not supported by protocol
EADDRINUSE 98 Address already in use
EADDRNOTAVAIL 99 Cannot assign requested address
ENETDOWN 100 Network is down
ENETUNREACH 101 Network is unreachable
ENETRESET 102 Network dropped connection on reset
ECONNABORTED 103 Software caused connection abort
ECONNRESET 104 Connection reset by peer
ENOBUFS 105 No buffer space available
EISCONN 106 Transport endpoint is already connected
ENOTCONN 107 Transport endpoint is not connected
ESHUTDOWN 108 Cannot send after transport endpoint shutdown
ETOOMANYREFS 109 Too many references: cannot splice
ETIMEDOUT 110 Connection timed out
ECONNREFUSED 111 Connection refused
EHOSTDOWN 112 Host is down
EHOSTUNREACH 113 No route to host
EALREADY 114 Operation already in progress
EINPROGRESS 115 Operation now in progress
ESTALE 116 Stale file handle
EUCLEAN 117 Structure needs cleaning
ENOTNAM 118 Not a XENIX named type file
ENAVAIL 119 No XENIX semaphores available
EISNAM 120 Is a named type file
EREMOTEIO 121 Remote I/O error
EDQUOT 122 Disk quota exceeded
ENOMEDIUM 123 No medium found
EMEDIUMTYPE 124 Wrong medium type
ECANCELED 125 Operation canceled
ENOKEY 126 Required key not available
EKEYEXPIRED 127 Key has expired
EKEYREVOKED 128 Key has been revoked
EKEYREJECTED 129 Key was rejected by service
EOWNERDEAD 130 Owner died
ENOTRECOVERABLE 131 State not recoverable
ERFKILL 132 Operation not possible due to RF-kill
EHWPOISON 133 Memory page has hardware error
ENOTSUP 95 Operation not supported

Programmers should handle all kinds of errors to protect the program from failure.

In C programming language, there is no direct support for error handling. You have to detect the failure and handle the error. In C programming language, return values represents success or failure. Inside a C program, when a function fails, you should handle the errors accordingly, or at least record the errors in a log file.

When you are running some program on Linux environment, you might notice that it gives some error number. For example, “Error no is : 17”, which doesn’t really say much. You really need to know what error number 17 means.

This article shows all available error numbers along with it descriptions. This article might be a handy reference for you, when you encounter an error number and you would like to know what it means.

  • In C programming language, there is an external variable called “errno”.
  • From this errno variable you can use some error handling functions to find out the error description and handle it appropriately.
  • You have to include errno.h header file to use external variable errno.
  • perror function prints error description in standard error.
  • The strerror function returns a string describing the error code passed in the argument errnum.

The following C code snippet tries to open a file through open system call. There are two flags in the open call. O_CREAT flag is to create a file, if the file does not exist. O_EXCL flag is used with O_CREAT, if the file is already exist open call will fail with the proper error number.

$ cat fileopen.c
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
main()
{
// Declaration of a file descriptor
int fd;

// Opening a file
fd = open("/root/sasikala/testing",O_CREAT|O_EXCL);
// If Open is failed
if ( fd < 0 ) {
        printf("Opening file : Failedn");
        printf ("Error no is : %dn", errno);
        printf("Error description is : %sn",strerror(errno));
}
// If Open is success
else
        printf("Opening file : Successn");

}

$ cc -o fileopen fileopen.c
$ ./fileopen

Opening file : Success

$ ./fileopen
Opening file : Failed
Error no is : 17
Error description is : File exists

At first execution, open got executed successfully, and it created the file since the file was not available. In next execution, it throws an error number 17, which is “File already exist”.

The following table shows list of error numbers and its descriptions in Linux operation system

ERROR CODE TABLE
Error number Error Code Error Description
1 EPERM Operation not permitted
2 ENOENT No such file or directory
3 ESRCH No such process
4 EINTR Interrupted system call
5 EIO I/O error
6 ENXIO No such device or address
7 E2BIG Argument list too long
8 ENOEXEC Exec format error
9 EBADF Bad file number
10 ECHILD No child processes
11 EAGAIN Try again
12 ENOMEM Out of memory
13 EACCES Permission denied
14 EFAULT Bad address
15 ENOTBLK Block device required
16 EBUSY Device or resource busy
17 EEXIST File exists
18 EXDEV Cross-device link
19 ENODEV No such device
20 ENOTDIR Not a directory
21 EISDIR Is a directory
22 EINVAL Invalid argument
23 ENFILE File table overflow
24 EMFILE Too many open files
25 ENOTTY Not a typewriter
26 ETXTBSY Text file busy
27 EFBIG File too large
28 ENOSPC No space left on device
29 ESPIPE Illegal seek
30 EROFS Read-only file system
31 EMLINK Too many links
32 EPIPE Broken pipe
33 EDOM Math argument out of domain of func
34 ERANGE Math result not representable
35 EDEADLK Resource deadlock would occur
36 ENAMETOOLONG File name too long
37 ENOLCK No record locks available
38 ENOSYS Function not implemented
39 ENOTEMPTY Directory not empty
40 ELOOP Too many symbolic links encountered
42 ENOMSG No message of desired type
43 EIDRM Identifier removed
44 ECHRNG Channel number out of range
45 EL2NSYNC Level 2 not synchronized
46 EL3HLT Level 3 halted
47 EL3RST Level 3 reset
48 ELNRNG Link number out of range
49 EUNATCH Protocol driver not attached
50 ENOCSI No CSI structure available
51 EL2HLT Level 2 halted
52 EBADE Invalid exchange
53 EBADR Invalid request descriptor
54 EXFULL Exchange full
55 ENOANO No anode
56 EBADRQC Invalid request code
57 EBADSLT Invalid slot
59 EBFONT Bad font file format
60 ENOSTR Device not a stream
61 ENODATA No data available
62 ETIME Timer expired
63 ENOSR Out of streams resources
64 ENONET Machine is not on the network
65 ENOPKG Package not installed
66 EREMOTE Object is remote
67 ENOLINK Link has been severed
68 EADV Advertise error
69 ESRMNT Srmount error
70 ECOMM Communication error on send
71 EPROTO Protocol error
72 EMULTIHOP Multihop attempted
73 EDOTDOT RFS specific error
74 EBADMSG Not a data message
75 EOVERFLOW Value too large for defined data type
76 ENOTUNIQ Name not unique on network
77 EBADFD File descriptor in bad state
78 EREMCHG Remote address changed
79 ELIBACC Can not access a needed shared library
80 ELIBBAD Accessing a corrupted shared library
81 ELIBSCN .lib section in a.out corrupted
82 ELIBMAX Attempting to link in too many shared libraries
83 ELIBEXEC Cannot exec a shared library directly
84 EILSEQ Illegal byte sequence
85 ERESTART Interrupted system call should be restarted
86 ESTRPIPE Streams pipe error
87 EUSERS Too many users
88 ENOTSOCK Socket operation on non-socket
89 EDESTADDRREQ Destination address required
90 EMSGSIZE Message too long
91 EPROTOTYPE Protocol wrong type for socket
92 ENOPROTOOPT Protocol not available
93 EPROTONOSUPPORT Protocol not supported
94 ESOCKTNOSUPPORT Socket type not supported
95 EOPNOTSUPP Operation not supported on transport endpoint
96 EPFNOSUPPORT Protocol family not supported
97 EAFNOSUPPORT Address family not supported by protocol
98 EADDRINUSE Address already in use
99 EADDRNOTAVAIL Cannot assign requested address
100 ENETDOWN Network is down
101 ENETUNREACH Network is unreachable
102 ENETRESET Network dropped connection because of reset
103 ECONNABORTED Software caused connection abort
104 ECONNRESET Connection reset by peer
105 ENOBUFS No buffer space available
106 EISCONN Transport endpoint is already connected
107 ENOTCONN Transport endpoint is not connected
108 ESHUTDOWN Cannot send after transport endpoint shutdown
109 ETOOMANYREFS Too many references: cannot splice
110 ETIMEDOUT Connection timed out
111 ECONNREFUSED Connection refused
112 EHOSTDOWN Host is down
113 EHOSTUNREACH No route to host
114 EALREADY Operation already in progress
115 EINPROGRESS Operation now in progress
116 ESTALE Stale NFS file handle
117 EUCLEAN Structure needs cleaning
118 ENOTNAM Not a XENIX named type file
119 ENAVAIL No XENIX semaphores available
120 EISNAM Is a named type file
121 EREMOTEIO Remote I/O error
122 EDQUOT Quota exceeded
123 ENOMEDIUM No medium found
124 EMEDIUMTYPE Wrong medium type
125 ECANCELED Operation Canceled
126 ENOKEY Required key not available
127 EKEYEXPIRED Key has expired
128 EKEYREVOKED Key has been revoked
129 EKEYREJECTED Key was rejected by service
130 EOWNERDEAD Owner died
131 ENOTRECOVERABLE State not recoverable

When you see an error number thrown by a C program on a Linux environment, you might find the above table handy to identify what those error number means. Make sure to bookmark this article for future reference.

Понравилась статья? Поделить с друзьями:
  • Errcur2000 ошибка альфа банк что это
  • Err 1 ошибка на частотнике
  • Err 016 ошибка измерителя нейтрального канала
  • Err8 стиральная машина haier ошибка
  • Err6 метаком ошибка