Errno(3)
number of last error
SYNOPSIS
#include <errno.h>
DESCRIPTION
The
<errno.h>
header file defines the integer variable
errno,
which is set by system calls and some library functions in the event
of an error to indicate what went wrong.
Its value is significant only when the return value of
the call indicated an error
(i.e., -1 from most system calls;
-1 or NULL from most library functions);
a function that succeeds
is
allowed to change
errno.
Valid error numbers are all nonzero;
errno
is never set to zero
by any system call or library function.
For some system calls and library functions (e.g.,
getpriority(2)),
-1 is a valid return on success.
In such cases, a successful return can be distinguished from an error
return by setting
errno
to zero before the call, and then,
if the call returns a status that indicates that an error
may have occurred, checking to see if
errno
has a nonzero value.
errno
is defined by the ISO C standard to be a modifiable lvalue
of type
int,
and must not be explicitly declared;
errno
may be a macro.
errno
is thread-local; setting it in one thread
does not affect its value in any other thread.
All the error names specified by POSIX.1
must have distinct values, with the exception of
EAGAIN
and
EWOULDBLOCK,
which may be the same.
Below is a list of the symbolic error names that are defined on Linux.
Some of these are marked
POSIX.1,
indicating that the name is defined by POSIX.1-2001, or
C99,
indicating that the name is defined by C99.
- E2BIG
- Argument list too long (POSIX.1)
- EACCES
- Permission denied (POSIX.1)
- EADDRINUSE
- Address already in use (POSIX.1)
- EADDRNOTAVAIL
- Address not available (POSIX.1)
- EAFNOSUPPORT
- Address family not supported (POSIX.1)
- EAGAIN
-
Resource temporarily unavailable (may be the same value as
EWOULDBLOCK)
(POSIX.1) - EALREADY
- Connection already in progress (POSIX.1)
- EBADE
- Invalid exchange
- EBADF
- Bad file descriptor (POSIX.1)
- EBADFD
- File descriptor in bad state
- EBADMSG
- Bad message (POSIX.1)
- EBADR
- Invalid request descriptor
- EBADRQC
- Invalid request code
- EBADSLT
- Invalid slot
- EBUSY
- Device or resource busy (POSIX.1)
- ECANCELED
- Operation canceled (POSIX.1)
- ECHILD
- No child processes (POSIX.1)
- ECHRNG
- Channel number out of range
- ECOMM
- Communication error on send
- ECONNABORTED
- Connection aborted (POSIX.1)
- ECONNREFUSED
- Connection refused (POSIX.1)
- ECONNRESET
- Connection reset (POSIX.1)
- EDEADLK
- Resource deadlock avoided (POSIX.1)
- EDEADLOCK
-
Synonym for
EDEADLK - EDESTADDRREQ
- Destination address required (POSIX.1)
- EDOM
- Mathematics argument out of domain of function (POSIX.1, C99)
- EDQUOT
- Disk quota exceeded (POSIX.1)
- EEXIST
- File exists (POSIX.1)
- EFAULT
- Bad address (POSIX.1)
- EFBIG
- File too large (POSIX.1)
- EHOSTDOWN
- Host is down
- EHOSTUNREACH
- Host is unreachable (POSIX.1)
- EIDRM
- Identifier removed (POSIX.1)
- EILSEQ
- Illegal byte sequence (POSIX.1, C99)
- EINPROGRESS
- Operation in progress (POSIX.1)
- EINTR
-
Interrupted function call (POSIX.1); see
signal(7). - EINVAL
- Invalid argument (POSIX.1)
- EIO
- Input/output error (POSIX.1)
- EISCONN
- Socket is connected (POSIX.1)
- EISDIR
- Is a directory (POSIX.1)
- EISNAM
- Is a named type file
- EKEYEXPIRED
- Key has expired
- EKEYREJECTED
- Key was rejected by service
- EKEYREVOKED
- Key has been revoked
- EL2HLT
- Level 2 halted
- EL2NSYNC
- Level 2 not synchronized
- EL3HLT
- Level 3 halted
- EL3RST
- Level 3 halted
- ELIBACC
- Cannot access a needed shared library
- ELIBBAD
- Accessing a corrupted shared library
- ELIBMAX
- Attempting to link in too many shared libraries
- ELIBSCN
- lib section in a.out corrupted
- ELIBEXEC
- Cannot exec a shared library directly
- ELOOP
- Too many levels of symbolic links (POSIX.1)
- EMEDIUMTYPE
- Wrong medium type
- EMFILE
-
Too many open files (POSIX.1);
commonly caused by exceeding the
RLIMIT_NOFILE
resource limit described in
getrlimit(2) - EMLINK
- Too many links (POSIX.1)
- EMSGSIZE
- Message too long (POSIX.1)
- EMULTIHOP
- Multihop attempted (POSIX.1)
- ENAMETOOLONG
- Filename too long (POSIX.1)
- ENETDOWN
- Network is down (POSIX.1)
- ENETRESET
- Connection aborted by network (POSIX.1)
- ENETUNREACH
- Network unreachable (POSIX.1)
- ENFILE
-
Too many open files in system (POSIX.1);
on Linux, this is probably a result of encountering the
/proc/sys/fs/file-max
limit (see
proc(5)). - ENOBUFS
- No buffer space available (POSIX.1 (XSI STREAMS option))
- ENODATA
- No message is available on the STREAM head read queue (POSIX.1)
- ENODEV
- No such device (POSIX.1)
- ENOENT
-
No such file or directory (POSIX.1)
Typically, this error results when a specified pathname does not exist,
or one of the components in the directory prefix of a pathname does not exist,
or the specified pathname is a dangling symbolic link. - ENOEXEC
- Exec format error (POSIX.1)
- ENOKEY
- Required key not available
- ENOLCK
- No locks available (POSIX.1)
- ENOLINK
- Link has been severed (POSIX.1)
- ENOMEDIUM
- No medium found
- ENOMEM
- Not enough space (POSIX.1)
- ENOMSG
- No message of the desired type (POSIX.1)
- ENONET
- Machine is not on the network
- ENOPKG
- Package not installed
- ENOPROTOOPT
- Protocol not available (POSIX.1)
- ENOSPC
- No space left on device (POSIX.1)
- ENOSR
- No STREAM resources (POSIX.1 (XSI STREAMS option))
- ENOSTR
- Not a STREAM (POSIX.1 (XSI STREAMS option))
- ENOSYS
- Function not implemented (POSIX.1)
- ENOTBLK
- Block device required
- ENOTCONN
- The socket is not connected (POSIX.1)
- ENOTDIR
- Not a directory (POSIX.1)
- ENOTEMPTY
- Directory not empty (POSIX.1)
- ENOTSOCK
- Not a socket (POSIX.1)
- ENOTSUP
- Operation not supported (POSIX.1)
- ENOTTY
- Inappropriate I/O control operation (POSIX.1)
- ENOTUNIQ
- Name not unique on network
- ENXIO
- No such device or address (POSIX.1)
- EOPNOTSUPP
-
Operation not supported on socket (POSIX.1)
(ENOTSUP
and
EOPNOTSUPP
have the same value on Linux, but
according to POSIX.1 these error values should be distinct.) - EOVERFLOW
- Value too large to be stored in data type (POSIX.1)
- EPERM
- Operation not permitted (POSIX.1)
- EPFNOSUPPORT
- Protocol family not supported
- EPIPE
- Broken pipe (POSIX.1)
- EPROTO
- Protocol error (POSIX.1)
- EPROTONOSUPPORT
- Protocol not supported (POSIX.1)
- EPROTOTYPE
- Protocol wrong type for socket (POSIX.1)
- ERANGE
- Result too large (POSIX.1, C99)
- EREMCHG
- Remote address changed
- EREMOTE
- Object is remote
- EREMOTEIO
- Remote I/O error
- ERESTART
- Interrupted system call should be restarted
- EROFS
- Read-only filesystem (POSIX.1)
- ESHUTDOWN
- Cannot send after transport endpoint shutdown
- ESPIPE
- Invalid seek (POSIX.1)
- ESOCKTNOSUPPORT
- Socket type not supported
- ESRCH
- No such process (POSIX.1)
- ESTALE
-
Stale file handle (POSIX.1)
This error can occur for NFS and for other filesystems
- ESTRPIPE
- Streams pipe error
- ETIME
-
Timer expired
(POSIX.1 (XSI STREAMS option))(POSIX.1 says «STREAM
ioctl(2)
timeout») - ETIMEDOUT
- Connection timed out (POSIX.1)
- ETXTBSY
- Text file busy (POSIX.1)
- EUCLEAN
- Structure needs cleaning
- EUNATCH
- Protocol driver not attached
- EUSERS
- Too many users
- EWOULDBLOCK
-
Operation would block (may be same value as
EAGAIN)
(POSIX.1) - EXDEV
- Improper link (POSIX.1)
- EXFULL
- Exchange full
NOTES
A common mistake is to do
if (somecall() == -1) { printf("somecall() failedn"); if (errno == ...) { ... } }
where
errno
no longer needs to have the value it had upon return from
somecall()
(i.e., it may have been changed by the
printf(3)).
If the value of
errno
should be preserved across a library call, it must be saved:
if (somecall() == -1) { int errsv = errno; printf("somecall() failedn"); if (errsv == ...) { ... } }
It was common in traditional C to declare
errno
manually
(i.e.,
extern int errno)
instead of including
<errno.h>.
Do not do this.
It will not work with modern versions of the C library.
However, on (very) old UNIX systems, there may be no
<errno.h>
and the declaration is needed.
COLOPHON
This page is part of release 4.06 of the Linux
man-pages
project.
A description of the project,
information about reporting bugs,
and the latest version of this page,
can be found at
https://www.kernel.org/doc/man-pages/.
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.
Each of the macros defined in <errno.h>
expands to an integer constant expression with type int and with a unique positive value. The following constants are defined by ISO C. The implementation may define more, as long as they begin with ‘E’ followed by digits or uppercase letters.
Defined in header |
|
Mathematics argument out of domain of function (macro constant) |
|
Illegal byte sequence (macro constant) |
|
Result too large (macro constant) |
[edit] Notes
Many additional errno constants are defined by POSIX and by the C++ standard library, and individual implementations may define even more, e.g. errno(3)
on Linux or intro(2)
on BSD and OS X.
[edit] Example
#include <stdio.h> #include <math.h> #include <errno.h> #include <string.h> int main(void) { errno = 0; printf("log(-1.0) = %fn", log(-1.0)); printf("%snn",strerror(errno)); errno = 0; printf("log(0.0) = %fn", log(0.0)); printf("%sn",strerror(errno)); }
Possible output:
log(-1.0) = nan Numerical argument out of domain log(0.0) = -inf Numerical result out of range
[edit] References
- C11 standard (ISO/IEC 9899:2011):
-
- 7.5/2 Errors <errno.h> (p: 205)
- C99 standard (ISO/IEC 9899:1999):
-
- 7.5/2 Errors <errno.h> (p: 186)
- C89/C90 standard (ISO/IEC 9899:1990):
-
- 4.1.3 Errors <errno.h>
[edit] See also
Improve Article
Save Article
Improve Article
Save Article
Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors at the first place and test return values from the functions.
A lot of C function calls return a -1 or NULL in case of an error, so quick test on these return values are easily done with for instance an ‘if statement’. For example, In Socket Programming, the returned value of the functions like socket(), listen() etc. are checked to see if there is an error or not.
Example: Error handling in Socket Programming
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); }
Different methods of Error handling in C
- Global Variable errno: When a function is called in C, a variable named as errno is automatically assigned a code (value) which can be used to identify the type of error that has been encountered. Its a global variable indicating the error occurred during any function call and defined in the header file errno.h.
Different codes (values) for errno mean different types of errors. Below is a list of few different errno values and its corresponding meaning:errno value Error 1 /* Operation not permitted */ 2 /* No such file or directory */ 3 /* No such process */ 4 /* Interrupted system call */ 5 /* I/O error */ 6 /* No such device or address */ 7 /* Argument list too long */ 8 /* Exec format error */ 9 /* Bad file number */ 10 /* No child processes */ 11 /* Try again */ 12 /* Out of memory */ 13 /* Permission denied */
#include <stdio.h>
#include <errno.h>
int
main()
{
FILE
* fp;
fp =
fopen
(
"GeeksForGeeks.txt"
,
"r"
);
printf
(
" Value of errno: %dn "
,
errno
);
return
0;
}
Output:
Value of errno: 2
Note: Here the errno is set to 2 which means – No such file or directory. On online IDE it may give errorno 13, which says permission denied.
- perror() and strerror(): The errno value got above indicate the types of error encountered.
If it is required to show the error description, then there are two functions that can be used to display a text message that is associated with errorno. The functions are:- perror: It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
Syntax:void perror (const char *str) str: is a string containing a custom message to be printed before the error message itself.
- strerror(): returns a pointer to the textual representation of the current errno value.
Syntax:char *strerror (int errnum) errnum: is the error number (errno).
#include <stdio.h>
#include <errno.h>
#include <string.h>
int
main ()
{
FILE
*fp;
fp =
fopen
(
" GeeksForGeeks.txt "
,
"r"
);
printf
(
"Value of errno: %dn "
,
errno
);
printf
(
"The error message is : %sn"
,
strerror
(
errno
));
perror
(
"Message from perror"
);
return
0;
}
Output:
On Personal desktop:Value of errno: 2 The error message is : No such file or directory Message from perror: No such file or directory
On online IDE:
Value of errno: 13 The error message is : Permission denied
Note: The function perror() displays a string passed to it, followed by a colon and the textual message of the current errno value.
- perror: It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
- Exit Status: The C standard specifies two constants: EXIT_SUCCESS and EXIT_FAILURE, that may be passed to exit() to indicate successful or unsuccessful termination, respectively. These are macros defined in stdlib.h.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int
main ()
{
FILE
* fp;
fp =
fopen
(
"filedoesnotexist.txt"
,
"rb"
);
if
(fp == NULL)
{
printf
(
"Value of errno: %dn"
,
errno
);
printf
(
"Error opening the file: %sn"
,
strerror
(
errno
));
perror
(
"Error printed by perror"
);
exit
(EXIT_FAILURE);
printf
(
"I will not be printedn"
);
}
else
{
fclose
(fp);
exit
(EXIT_SUCCESS);
printf
(
"I will not be printedn"
);
}
return
0;
}
Output:
Value of errno: 2 Error opening the file: No such file or directory Error printed by perror: No such file or directory
- Divide by Zero Errors: A common pitfall made by C programmers is not checking if a divisor is zero before a division command. Division by zero leads to undefined behavior, there is no C language construct that can do anything about it. Your best bet is to not divide by zero in the first place, by checking the denominator.
#include<stdio.h>
#include <stdlib.h>
void
function(
int
);
int
main()
{
int
x = 0;
function(x);
return
0;
}
void
function(
int
x)
{
float
fx;
if
(x==0)
{
printf
(
"Division by Zero is not allowed"
);
fprintf
(stderr,
"Division by zero! Exiting...n"
);
exit
(EXIT_FAILURE);
}
else
{
fx = 10 / x;
printf
(
"f(x) is: %.5f"
, fx);
}
}
Output:
Division by Zero is not allowed
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.