The names and meanings (but not the values) of these error codes are defined by POSIX.
More…
Macros |
|
| #define | ENOERR __einfo_error ( EINFO_ENOERR ) |
| Operation completed successfully. More… | |
| #define | EINFO_ENOERR |
| #define | E2BIG __einfo_error ( EINFO_E2BIG ) |
| Argument list too long. More… | |
| #define | EINFO_E2BIG |
| #define | EACCES __einfo_error ( EINFO_EACCES ) |
| Permission denied. More… | |
| #define | EINFO_EACCES |
| #define | EADDRINUSE __einfo_error ( EINFO_EADDRINUSE ) |
| Address already in use. More… | |
| #define | EINFO_EADDRINUSE |
| #define | EADDRNOTAVAIL __einfo_error ( EINFO_EADDRNOTAVAIL ) |
| Address not available. More… | |
| #define | EINFO_EADDRNOTAVAIL |
| #define | EAFNOSUPPORT __einfo_error ( EINFO_EAFNOSUPPORT ) |
| Address family not supported. More… | |
| #define | EINFO_EAFNOSUPPORT |
| #define | EAGAIN __einfo_error ( EINFO_EAGAIN ) |
| Resource temporarily unavailable. More… | |
| #define | EINFO_EAGAIN |
| #define | EALREADY __einfo_error ( EINFO_EALREADY ) |
| Connection already in progress. More… | |
| #define | EINFO_EALREADY |
| #define | EBADF __einfo_error ( EINFO_EBADF ) |
| Bad file descriptor. More… | |
| #define | EINFO_EBADF |
| #define | EBADMSG __einfo_error ( EINFO_EBADMSG ) |
| Bad message. More… | |
| #define | EINFO_EBADMSG |
| #define | EBUSY __einfo_error ( EINFO_EBUSY ) |
| Device or resource busy. More… | |
| #define | EINFO_EBUSY |
| #define | ECANCELED __einfo_error ( EINFO_ECANCELED ) |
| Operation canceled. More… | |
| #define | EINFO_ECANCELED |
| #define | ECHILD __einfo_error ( EINFO_ECHILD ) |
| No child processes. More… | |
| #define | EINFO_ECHILD |
| #define | ECONNABORTED __einfo_error ( EINFO_ECONNABORTED ) |
| Connection aborted. More… | |
| #define | EINFO_ECONNABORTED |
| #define | ECONNREFUSED __einfo_error ( EINFO_ECONNREFUSED ) |
| Connection refused. More… | |
| #define | EINFO_ECONNREFUSED |
| #define | ECONNRESET __einfo_error ( EINFO_ECONNRESET ) |
| Connection reset. More… | |
| #define | EINFO_ECONNRESET |
| #define | EDEADLK __einfo_error ( EINFO_EDEADLK ) |
| Resource deadlock avoided. More… | |
| #define | EINFO_EDEADLK |
| #define | EDESTADDRREQ __einfo_error ( EINFO_EDESTADDRREQ ) |
| Destination address required. More… | |
| #define | EINFO_EDESTADDRREQ |
| #define | EDOM __einfo_error ( EINFO_EDOM ) |
| Mathematics argument out of domain of function. More… | |
| #define | EINFO_EDOM |
| #define | EDQUOT __einfo_error ( EINFO_EDQUOT ) |
| Disk quota exceeded. More… | |
| #define | EINFO_EDQUOT |
| #define | EEXIST __einfo_error ( EINFO_EEXIST ) |
| File exists. More… | |
| #define | EINFO_EEXIST |
| #define | EFAULT __einfo_error ( EINFO_EFAULT ) |
| Bad address. More… | |
| #define | EINFO_EFAULT |
| #define | EFBIG __einfo_error ( EINFO_EFBIG ) |
| File too large. More… | |
| #define | EINFO_EFBIG |
| #define | EHOSTUNREACH __einfo_error ( EINFO_EHOSTUNREACH ) |
| Host is unreachable. More… | |
| #define | EINFO_EHOSTUNREACH |
| #define | EIDRM __einfo_error ( EINFO_EIDRM ) |
| Identifier removed. More… | |
| #define | EINFO_EIDRM |
| #define | EILSEQ __einfo_error ( EINFO_EILSEQ ) |
| Illegal byte sequence. More… | |
| #define | EINFO_EILSEQ |
| #define | EINPROGRESS __einfo_error ( EINFO_EINPROGRESS ) |
| Operation in progress. More… | |
| #define | EINFO_EINPROGRESS |
| #define | EINTR __einfo_error ( EINFO_EINTR ) |
| Interrupted function call. More… | |
| #define | EINFO_EINTR |
| #define | EINVAL __einfo_error ( EINFO_EINVAL ) |
| Invalid argument. More… | |
| #define | EINFO_EINVAL |
| #define | EIO __einfo_error ( EINFO_EIO ) |
| Input/output error. More… | |
| #define | EINFO_EIO |
| #define | EISCONN __einfo_error ( EINFO_EISCONN ) |
| Socket is connected. More… | |
| #define | EINFO_EISCONN |
| #define | EISDIR __einfo_error ( EINFO_EISDIR ) |
| Is a directory. More… | |
| #define | EINFO_EISDIR |
| #define | ELOOP __einfo_error ( EINFO_ELOOP ) |
| Too many levels of symbolic links. More… | |
| #define | EINFO_ELOOP |
| #define | EMFILE __einfo_error ( EINFO_EMFILE ) |
| Too many open files. More… | |
| #define | EINFO_EMFILE |
| #define | EMLINK __einfo_error ( EINFO_EMLINK ) |
| Too many links. More… | |
| #define | EINFO_EMLINK |
| #define | EMSGSIZE __einfo_error ( EINFO_EMSGSIZE ) |
| Message too long. More… | |
| #define | EINFO_EMSGSIZE |
| #define | EMULTIHOP __einfo_error ( EINFO_EMULTIHOP ) |
| Multihop attempted. More… | |
| #define | EINFO_EMULTIHOP |
| #define | ENAMETOOLONG __einfo_error ( EINFO_ENAMETOOLONG ) |
| Filename too long. More… | |
| #define | EINFO_ENAMETOOLONG |
| #define | ENETDOWN __einfo_error ( EINFO_ENETDOWN ) |
| Network is down. More… | |
| #define | EINFO_ENETDOWN |
| #define | ENETRESET __einfo_error ( EINFO_ENETRESET ) |
| Connection aborted by network. More… | |
| #define | EINFO_ENETRESET |
| #define | ENETUNREACH __einfo_error ( EINFO_ENETUNREACH ) |
| Network unreachable. More… | |
| #define | EINFO_ENETUNREACH |
| #define | ENFILE __einfo_error ( EINFO_ENFILE ) |
| Too many open files in system. More… | |
| #define | EINFO_ENFILE |
| #define | ENOBUFS __einfo_error ( EINFO_ENOBUFS ) |
| No buffer space available. More… | |
| #define | EINFO_ENOBUFS |
| #define | ENODATA __einfo_error ( EINFO_ENODATA ) |
| No message is available on the STREAM head read queue. More… | |
| #define | EINFO_ENODATA |
| #define | ENODEV __einfo_error ( EINFO_ENODEV ) |
| No such device. More… | |
| #define | EINFO_ENODEV |
| #define | ENOENT __einfo_error ( EINFO_ENOENT ) |
| No such file or directory. More… | |
| #define | EINFO_ENOENT |
| #define | ENOEXEC __einfo_error ( EINFO_ENOEXEC ) |
| Exec format error. More… | |
| #define | EINFO_ENOEXEC |
| #define | ENOLCK __einfo_error ( EINFO_ENOLCK ) |
| No locks available. More… | |
| #define | EINFO_ENOLCK |
| #define | ENOLINK __einfo_error ( EINFO_ENOLINK ) |
| Link has been severed. More… | |
| #define | EINFO_ENOLINK |
| #define | ENOMEM __einfo_error ( EINFO_ENOMEM ) |
| Not enough space. More… | |
| #define | EINFO_ENOMEM |
| #define | ENOMSG __einfo_error ( EINFO_ENOMSG ) |
| No message of the desired type. More… | |
| #define | EINFO_ENOMSG |
| #define | ENOPROTOOPT __einfo_error ( EINFO_ENOPROTOOPT ) |
| Protocol not available. More… | |
| #define | EINFO_ENOPROTOOPT |
| #define | ENOSPC __einfo_error ( EINFO_ENOSPC ) |
| No space left on device. More… | |
| #define | EINFO_ENOSPC |
| #define | ENOSR __einfo_error ( EINFO_ENOSR ) |
| No STREAM resources. More… | |
| #define | EINFO_ENOSR |
| #define | ENOSTR __einfo_error ( EINFO_ENOSTR ) |
| Not a STREAM. More… | |
| #define | EINFO_ENOSTR |
| #define | ENOSYS __einfo_error ( EINFO_ENOSYS ) |
| Function not implemented. More… | |
| #define | EINFO_ENOSYS |
| #define | ENOTCONN __einfo_error ( EINFO_ENOTCONN ) |
| The socket is not connected. More… | |
| #define | EINFO_ENOTCONN |
| #define | ENOTDIR __einfo_error ( EINFO_ENOTDIR ) |
| Not a directory. More… | |
| #define | EINFO_ENOTDIR |
| #define | ENOTEMPTY __einfo_error ( EINFO_ENOTEMPTY ) |
| Directory not empty. More… | |
| #define | EINFO_ENOTEMPTY |
| #define | ENOTSOCK __einfo_error ( EINFO_ENOTSOCK ) |
| Not a socket. More… | |
| #define | EINFO_ENOTSOCK |
| #define | ENOTSUP __einfo_error ( EINFO_ENOTSUP ) |
| Operation not supported. More… | |
| #define | EINFO_ENOTSUP |
| #define | ENOTTY __einfo_error ( EINFO_ENOTTY ) |
| Inappropriate I/O control operation. More… | |
| #define | EINFO_ENOTTY |
| #define | ENXIO __einfo_error ( EINFO_ENXIO ) |
| No such device or address. More… | |
| #define | EINFO_ENXIO |
| #define | EOPNOTSUPP __einfo_error ( EINFO_EOPNOTSUPP ) |
| Operation not supported on socket. More… | |
| #define | EINFO_EOPNOTSUPP |
| #define | EOVERFLOW __einfo_error ( EINFO_EOVERFLOW ) |
| Value too large to be stored in data type. More… | |
| #define | EINFO_EOVERFLOW |
| #define | EPERM __einfo_error ( EINFO_EPERM ) |
| Operation not permitted. More… | |
| #define | EINFO_EPERM |
| #define | EPIPE __einfo_error ( EINFO_EPIPE ) |
| Broken pipe. More… | |
| #define | EINFO_EPIPE |
| #define | EPROTO __einfo_error ( EINFO_EPROTO ) |
| Protocol error. More… | |
| #define | EINFO_EPROTO |
| #define | EPROTONOSUPPORT __einfo_error ( EINFO_EPROTONOSUPPORT ) |
| Protocol not supported. More… | |
| #define | EINFO_EPROTONOSUPPORT |
| #define | EPROTOTYPE __einfo_error ( EINFO_EPROTOTYPE ) |
| Protocol wrong type for socket. More… | |
| #define | EINFO_EPROTOTYPE |
| #define | ERANGE __einfo_error ( EINFO_ERANGE ) |
| Result too large. More… | |
| #define | EINFO_ERANGE |
| #define | EROFS __einfo_error ( EINFO_EROFS ) |
| Read-only file system. More… | |
| #define | EINFO_EROFS |
| #define | ESPIPE __einfo_error ( EINFO_ESPIPE ) |
| Invalid seek. More… | |
| #define | EINFO_ESPIPE |
| #define | ESRCH __einfo_error ( EINFO_ESRCH ) |
| No such process. More… | |
| #define | EINFO_ESRCH |
| #define | ESTALE __einfo_error ( EINFO_ESTALE ) |
| Stale file handle. More… | |
| #define | EINFO_ESTALE |
| #define | ETIME __einfo_error ( EINFO_ETIME ) |
| Timer expired. More… | |
| #define | EINFO_ETIME |
| #define | ETIMEDOUT __einfo_error ( EINFO_ETIMEDOUT ) |
| Connection timed out. More… | |
| #define | EINFO_ETIMEDOUT |
| #define | ETXTBSY __einfo_error ( EINFO_ETXTBSY ) |
| Text file busy. More… | |
| #define | EINFO_ETXTBSY |
| #define | EWOULDBLOCK __einfo_error ( EINFO_EWOULDBLOCK ) |
| Operation would block. More… | |
| #define | EINFO_EWOULDBLOCK |
| #define | EXDEV __einfo_error ( EINFO_EXDEV ) |
| Improper link. More… | |
| #define | EINFO_EXDEV |
The names and meanings (but not the values) of these error codes are defined by POSIX.
◆ ENOERR
Operation completed successfully.
Definition at line 288 of file errno.h.
◆ EINFO_ENOERR
Value:
«Operation completed successfully» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 289 of file errno.h.
◆ E2BIG
Argument list too long.
Definition at line 293 of file errno.h.
◆ EINFO_E2BIG
Value:
«Argument list too long» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 294 of file errno.h.
◆ EACCES
Permission denied.
Definition at line 298 of file errno.h.
◆ EINFO_EACCES
Value:
«Permission denied» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 299 of file errno.h.
◆ EADDRINUSE
Address already in use.
Definition at line 303 of file errno.h.
◆ EINFO_EADDRINUSE
Value:
«Address already in use» )
#define PLATFORM_EADDRINUSE
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 304 of file errno.h.
◆ EADDRNOTAVAIL
Address not available.
Definition at line 308 of file errno.h.
◆ EINFO_EADDRNOTAVAIL
#define EINFO_EADDRNOTAVAIL
Value:
«Address not available» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EADDRNOTAVAIL
Definition at line 309 of file errno.h.
◆ EAFNOSUPPORT
Address family not supported.
Definition at line 313 of file errno.h.
◆ EINFO_EAFNOSUPPORT
#define EINFO_EAFNOSUPPORT
Value:
«Address family not supported» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EAFNOSUPPORT
Definition at line 314 of file errno.h.
◆ EAGAIN
Resource temporarily unavailable.
Definition at line 318 of file errno.h.
◆ EINFO_EAGAIN
Value:
«Resource temporarily unavailable» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 319 of file errno.h.
◆ EALREADY
Connection already in progress.
Definition at line 323 of file errno.h.
◆ EINFO_EALREADY
Value:
«Connection already in progress» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EALREADY
Definition at line 324 of file errno.h.
◆ EBADF
Bad file descriptor.
Definition at line 328 of file errno.h.
◆ EINFO_EBADF
Value:
«Bad file descriptor» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 329 of file errno.h.
◆ EBADMSG
Bad message.
Definition at line 333 of file errno.h.
◆ EINFO_EBADMSG
Value:
«Bad message» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 334 of file errno.h.
◆ EBUSY
Device or resource busy.
Definition at line 338 of file errno.h.
◆ EINFO_EBUSY
Value:
«Device or resource busy» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 339 of file errno.h.
◆ ECANCELED
Operation canceled.
Definition at line 343 of file errno.h.
◆ EINFO_ECANCELED
Value:
«Operation canceled» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ECANCELED
Definition at line 344 of file errno.h.
◆ ECHILD
No child processes.
Definition at line 348 of file errno.h.
◆ EINFO_ECHILD
Value:
«No child processes» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 349 of file errno.h.
◆ ECONNABORTED
Connection aborted.
Definition at line 353 of file errno.h.
◆ EINFO_ECONNABORTED
#define EINFO_ECONNABORTED
Value:
«Connection aborted» )
#define PLATFORM_ECONNABORTED
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 354 of file errno.h.
◆ ECONNREFUSED
Connection refused.
Definition at line 358 of file errno.h.
◆ EINFO_ECONNREFUSED
#define EINFO_ECONNREFUSED
Value:
«Connection refused» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ECONNREFUSED
Definition at line 359 of file errno.h.
◆ ECONNRESET
Connection reset.
Definition at line 363 of file errno.h.
◆ EINFO_ECONNRESET
Value:
«Connection reset» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ECONNRESET
Definition at line 364 of file errno.h.
◆ EDEADLK
Resource deadlock avoided.
Definition at line 368 of file errno.h.
◆ EINFO_EDEADLK
Value:
«Resource deadlock avoided» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 369 of file errno.h.
◆ EDESTADDRREQ
Destination address required.
Definition at line 373 of file errno.h.
◆ EINFO_EDESTADDRREQ
#define EINFO_EDESTADDRREQ
Value:
«Destination address required» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EDESTADDRREQ
Definition at line 374 of file errno.h.
◆ EDOM
Mathematics argument out of domain of function.
Definition at line 378 of file errno.h.
◆ EINFO_EDOM
Value:
«Mathematics argument out of domain of function» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 379 of file errno.h.
◆ EDQUOT
Disk quota exceeded.
Definition at line 383 of file errno.h.
◆ EINFO_EDQUOT
Value:
«Disk quote exceeded» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 384 of file errno.h.
◆ EEXIST
File exists.
Definition at line 388 of file errno.h.
◆ EINFO_EEXIST
Value:
«File exists» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 389 of file errno.h.
◆ EFAULT
Bad address.
Definition at line 393 of file errno.h.
◆ EINFO_EFAULT
Value:
«Bad address» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 394 of file errno.h.
◆ EFBIG
File too large.
Definition at line 398 of file errno.h.
◆ EINFO_EFBIG
Value:
«File too large» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 399 of file errno.h.
◆ EHOSTUNREACH
Host is unreachable.
Definition at line 403 of file errno.h.
◆ EINFO_EHOSTUNREACH
#define EINFO_EHOSTUNREACH
Value:
«Host is unreachable» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EHOSTUNREACH
Definition at line 404 of file errno.h.
◆ EIDRM
Identifier removed.
Definition at line 408 of file errno.h.
◆ EINFO_EIDRM
Value:
«Identifier removed» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 409 of file errno.h.
◆ EILSEQ
Illegal byte sequence.
Definition at line 413 of file errno.h.
◆ EINFO_EILSEQ
Value:
«Illegal byte sequence» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 414 of file errno.h.
◆ EINPROGRESS
Operation in progress.
Definition at line 418 of file errno.h.
◆ EINFO_EINPROGRESS
#define EINFO_EINPROGRESS
Value:
«Operation in progress» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EINPROGRESS
Definition at line 419 of file errno.h.
◆ EINTR
Interrupted function call.
Definition at line 423 of file errno.h.
◆ EINFO_EINTR
Value:
«Interrupted function call» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 424 of file errno.h.
◆ EINVAL
Invalid argument.
Definition at line 428 of file errno.h.
◆ EINFO_EINVAL
Value:
«Invalid argument» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 429 of file errno.h.
◆ EIO
Input/output error.
Definition at line 433 of file errno.h.
◆ EINFO_EIO
Value:
«Input/output error» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 434 of file errno.h.
◆ EISCONN
Socket is connected.
Definition at line 438 of file errno.h.
◆ EINFO_EISCONN
Value:
«Socket is connected» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 439 of file errno.h.
◆ EISDIR
Is a directory.
Definition at line 443 of file errno.h.
◆ EINFO_EISDIR
Value:
«Is a directory» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 444 of file errno.h.
◆ ELOOP
Too many levels of symbolic links.
Definition at line 448 of file errno.h.
◆ EINFO_ELOOP
Value:
«Too many levels of symbolic links» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 449 of file errno.h.
◆ EMFILE
Too many open files.
Definition at line 453 of file errno.h.
◆ EINFO_EMFILE
Value:
«Too many open files» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 454 of file errno.h.
◆ EMLINK
Too many links.
Definition at line 458 of file errno.h.
◆ EINFO_EMLINK
Value:
«Too many links» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 459 of file errno.h.
◆ EMSGSIZE
Message too long.
Definition at line 463 of file errno.h.
◆ EINFO_EMSGSIZE
Value:
«Message too long» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EMSGSIZE
Definition at line 464 of file errno.h.
◆ EMULTIHOP
Multihop attempted.
Definition at line 468 of file errno.h.
◆ EINFO_EMULTIHOP
Value:
«Multihop attempted» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EMULTIHOP
Definition at line 469 of file errno.h.
◆ ENAMETOOLONG
Filename too long.
Definition at line 473 of file errno.h.
◆ EINFO_ENAMETOOLONG
#define EINFO_ENAMETOOLONG
Value:
«Filename too long» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENAMETOOLONG
Definition at line 474 of file errno.h.
◆ ENETDOWN
Network is down.
Definition at line 478 of file errno.h.
◆ EINFO_ENETDOWN
Value:
«Network is down» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENETDOWN
Definition at line 479 of file errno.h.
◆ ENETRESET
Connection aborted by network.
Definition at line 483 of file errno.h.
◆ EINFO_ENETRESET
Value:
«Connection aborted by network» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENETRESET
Definition at line 484 of file errno.h.
◆ ENETUNREACH
Network unreachable.
Definition at line 488 of file errno.h.
◆ EINFO_ENETUNREACH
#define EINFO_ENETUNREACH
Value:
«Network unreachable» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENETUNREACH
Definition at line 489 of file errno.h.
◆ ENFILE
Too many open files in system.
Definition at line 493 of file errno.h.
◆ EINFO_ENFILE
Value:
«Too many open files in system» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 494 of file errno.h.
◆ ENOBUFS
No buffer space available.
Definition at line 498 of file errno.h.
◆ EINFO_ENOBUFS
Value:
«No buffer space available» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 499 of file errno.h.
◆ ENODATA
No message is available on the STREAM head read queue.
Definition at line 503 of file errno.h.
◆ EINFO_ENODATA
Value:
«No message is available on the STREAM «
«head read queue» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 504 of file errno.h.
◆ ENODEV
No such device.
Definition at line 509 of file errno.h.
◆ EINFO_ENODEV
Value:
«No such device» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 510 of file errno.h.
◆ ENOENT
No such file or directory.
Definition at line 514 of file errno.h.
◆ EINFO_ENOENT
Value:
«No such file or directory» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 515 of file errno.h.
◆ ENOEXEC
Exec format error.
Definition at line 519 of file errno.h.
◆ EINFO_ENOEXEC
Value:
«Exec format error» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 520 of file errno.h.
◆ ENOLCK
No locks available.
Definition at line 524 of file errno.h.
◆ EINFO_ENOLCK
Value:
«No locks available» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 525 of file errno.h.
◆ ENOLINK
Link has been severed.
Definition at line 529 of file errno.h.
◆ EINFO_ENOLINK
Value:
«Link has been severed» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 530 of file errno.h.
◆ ENOMEM
Not enough space.
Definition at line 534 of file errno.h.
◆ EINFO_ENOMEM
Value:
«Not enough space» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 535 of file errno.h.
◆ ENOMSG
No message of the desired type.
Definition at line 539 of file errno.h.
◆ EINFO_ENOMSG
Value:
«No message of the desired type» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 540 of file errno.h.
◆ ENOPROTOOPT
Protocol not available.
Definition at line 544 of file errno.h.
◆ EINFO_ENOPROTOOPT
#define EINFO_ENOPROTOOPT
Value:
«Protocol not available» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENOPROTOOPT
Definition at line 545 of file errno.h.
◆ ENOSPC
No space left on device.
Definition at line 549 of file errno.h.
◆ EINFO_ENOSPC
Value:
«No space left on device» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 550 of file errno.h.
◆ ENOSR
No STREAM resources.
Definition at line 554 of file errno.h.
◆ EINFO_ENOSR
Value:
«No STREAM resources» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 555 of file errno.h.
◆ ENOSTR
Not a STREAM.
Definition at line 559 of file errno.h.
◆ EINFO_ENOSTR
Value:
«Not a STREAM» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 560 of file errno.h.
◆ ENOSYS
Function not implemented.
Definition at line 564 of file errno.h.
◆ EINFO_ENOSYS
Value:
«Function not implemented» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 565 of file errno.h.
◆ ENOTCONN
The socket is not connected.
Definition at line 569 of file errno.h.
◆ EINFO_ENOTCONN
Value:
«The socket is not connected» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENOTCONN
Definition at line 570 of file errno.h.
◆ ENOTDIR
Not a directory.
Definition at line 574 of file errno.h.
◆ EINFO_ENOTDIR
Value:
«Not a directory» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 575 of file errno.h.
◆ ENOTEMPTY
Directory not empty.
Definition at line 579 of file errno.h.
◆ EINFO_ENOTEMPTY
Value:
«Directory not empty» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENOTEMPTY
Definition at line 580 of file errno.h.
◆ ENOTSOCK
Not a socket.
Definition at line 584 of file errno.h.
◆ EINFO_ENOTSOCK
Value:
«Not a socket» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_ENOTSOCK
Definition at line 585 of file errno.h.
◆ ENOTSUP
Operation not supported.
Definition at line 589 of file errno.h.
◆ EINFO_ENOTSUP
Value:
«Operation not supported» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 590 of file errno.h.
◆ ENOTTY
Inappropriate I/O control operation.
Definition at line 594 of file errno.h.
◆ EINFO_ENOTTY
Value:
«Inappropriate I/O control operation» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 595 of file errno.h.
◆ ENXIO
No such device or address.
Definition at line 599 of file errno.h.
◆ EINFO_ENXIO
Value:
«No such device or address» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 600 of file errno.h.
◆ EOPNOTSUPP
Operation not supported on socket.
Definition at line 604 of file errno.h.
◆ EINFO_EOPNOTSUPP
Value:
«Operation not supported on socket» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EOPNOTSUPP
Definition at line 605 of file errno.h.
◆ EOVERFLOW
Value too large to be stored in data type.
Definition at line 609 of file errno.h.
◆ EINFO_EOVERFLOW
Value:
«Value too large to be stored in data type» )
#define PLATFORM_EOVERFLOW
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 610 of file errno.h.
◆ EPERM
Operation not permitted.
Definition at line 614 of file errno.h.
◆ EINFO_EPERM
Value:
«Operation not permitted» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 615 of file errno.h.
◆ EPIPE
Broken pipe.
Definition at line 619 of file errno.h.
◆ EINFO_EPIPE
Value:
«Broken pipe» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 620 of file errno.h.
◆ EPROTO
Protocol error.
Definition at line 624 of file errno.h.
◆ EINFO_EPROTO
Value:
«Protocol error» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 625 of file errno.h.
◆ EPROTONOSUPPORT
Protocol not supported.
Definition at line 629 of file errno.h.
◆ EINFO_EPROTONOSUPPORT
#define EINFO_EPROTONOSUPPORT
Value:
«Protocol not supported» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EPROTONOSUPPORT
Definition at line 630 of file errno.h.
◆ EPROTOTYPE
Protocol wrong type for socket.
Definition at line 634 of file errno.h.
◆ EINFO_EPROTOTYPE
Value:
«Protocol wrong type for socket» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EPROTOTYPE
Definition at line 635 of file errno.h.
◆ ERANGE
Result too large.
Definition at line 639 of file errno.h.
◆ EINFO_ERANGE
Value:
«Result too large» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 640 of file errno.h.
◆ EROFS
Read-only file system.
Definition at line 644 of file errno.h.
◆ EINFO_EROFS
Value:
«Read-only file system» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 645 of file errno.h.
◆ ESPIPE
Invalid seek.
Definition at line 649 of file errno.h.
◆ EINFO_ESPIPE
Value:
«Invalid seek» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 650 of file errno.h.
◆ ESRCH
No such process.
Definition at line 654 of file errno.h.
◆ EINFO_ESRCH
Value:
«No such process» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 655 of file errno.h.
◆ ESTALE
Stale file handle.
Definition at line 659 of file errno.h.
◆ EINFO_ESTALE
Value:
«Stale file handle» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 660 of file errno.h.
◆ ETIME
Timer expired.
Definition at line 664 of file errno.h.
◆ EINFO_ETIME
Value:
«Timer expired» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 665 of file errno.h.
◆ ETIMEDOUT
Connection timed out.
Definition at line 669 of file errno.h.
◆ EINFO_ETIMEDOUT
Value:
«Connection timed out» )
#define PLATFORM_ETIMEDOUT
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 670 of file errno.h.
◆ ETXTBSY
Text file busy.
Definition at line 674 of file errno.h.
◆ EINFO_ETXTBSY
Value:
«Text file busy» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 675 of file errno.h.
◆ EWOULDBLOCK
Operation would block.
Definition at line 679 of file errno.h.
◆ EINFO_EWOULDBLOCK
#define EINFO_EWOULDBLOCK
Value:
«Operation would block» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
#define PLATFORM_EWOULDBLOCK
Definition at line 680 of file errno.h.
◆ EXDEV
Improper link.
Definition at line 684 of file errno.h.
◆ EINFO_EXDEV
Value:
«Improper link» )
#define __einfo(platform, posix, uniq, desc)
Declare error information.
Definition at line 685 of file errno.h.
Время на прочтение
13 мин
Количество просмотров 74K
Введение
Ошибки, увы, неизбежны, поэтому их обработка занимает очень важное место в программировании. И если алгоритмические ошибки можно выявить и исправить во время написания и тестирования программы, то ошибок времени выполнения избежать нельзя в принципе. Сегодня мы рассмотрим функции стандартной библиотеки (C Standard Library) и POSIX, используемые в обработке ошибок.
Переменная errno и коды ошибок
<errno.h>
errno – переменная, хранящая целочисленный код последней ошибки. В каждом потоке существует своя локальная версия errno, чем и обусловливается её безопасность в многопоточной среде. Обычно errno реализуется в виде макроса, разворачивающегося в вызов функции, возвращающей указатель на целочисленный буфер. При запуске программы значение errno равно нулю.
Все коды ошибок имеют положительные значения, и могут использоваться в директивах препроцессора #if. В целях удобства и переносимости заголовочный файл <errno.h> определяет макросы, соответствующие кодам ошибок.
Стандарт ISO C определяет следующие коды:
- EDOM – (Error domain) ошибка области определения.
- EILSEQ – (Error invalid sequence) ошибочная последовательность байтов.
- ERANGE – (Error range) результат слишком велик.
Прочие коды ошибок (несколько десятков) и их описания определены в стандарте POSIX. Кроме того, в спецификациях стандартных функций обычно указываются используемые ими коды ошибок и их описания.
Нехитрый скрипт печатает в консоль коды ошибок, их символические имена и описания:
#!/usr/bin/perl
use strict;
use warnings;
use Errno;
foreach my $err (sort keys (%!)) {
$! = eval "Errno::$err";
printf "%20s %4d %sn", $err, $! + 0, $!
}
Если вызов функции завершился ошибкой, то она устанавливает переменную errno в ненулевое значение. Если же вызов прошёл успешно, функция обычно не проверяет и не меняет переменную errno. Поэтому перед вызовом функции её нужно установить в 0.
Пример:
/* convert from UTF16 to UTF8 */
errno = 0;
n_ret = iconv(icd, (char **) &p_src, &n_src, &p_dst, &n_dst);
if (n_ret == (size_t) -1) {
VJ_PERROR();
if (errno == E2BIG)
fprintf(stderr, " Error : input conversion stopped due to lack of space in the output buffern");
else if (errno == EILSEQ)
fprintf(stderr, " Error : input conversion stopped due to an input byte that does not belong to the input codesetn");
else if (errno == EINVAL)
fprintf(stderr, " Error : input conversion stopped due to an incomplete character or shift sequence at the end of the input buffern");
/* clean the memory */
free(p_out_buf);
errno = 0;
n_ret = iconv_close(icd);
if (n_ret == (size_t) -1)
VJ_PERROR();
return (size_t) -1;
}
Как видите, описания ошибок в спецификации функции iconv() более информативны, чем в <errno.h>.
Функции работы с errno
Получив код ошибки, хочется сразу получить по нему её описание. К счастью, ISO C предлагает целый набор полезных функций.
<stdio.h>
void perror(const char *s);
Печатает в stderr содержимое строки s, за которой следует двоеточие, пробел и сообщение об ошибке. После чего печатает символ новой строки 'n'.
Пример:
/*
// main.c
// perror example
//
// Created by Ariel Feinerman on 23/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, const char * argv[])
{
// Generate unique filename.
char *file_name = tmpnam((char[L_tmpnam]){0});
errno = 0;
FILE *file = fopen(file_name, "rb");
if (file) {
// Do something useful.
fclose(file);
}
else {
perror("fopen() ");
}
return EXIT_SUCCESS;
}
<string.h>
char* strerror(int errnum);
Возвращает строку, содержащую описание ошибки errnum. Язык сообщения зависит от локали (немецкий, иврит и даже японский), но обычно поддерживается лишь английский.
/*
// main.c
// strerror example
//
// Created by Ariel Feinerman on 23/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, const char * argv[])
{
// Generate unique filename.
char *file_name = tmpnam((char[L_tmpnam]){0});
errno = 0;
FILE *file = fopen(file_name, "rb");
// Save error number.
errno_t error_num = errno;
if (file) {
// Do something useful.
fclose(file);
}
else {
char *errorbuf = strerror(error_num);
fprintf(stderr, "Error message : %sn", errorbuf);
}
return EXIT_SUCCESS;
}
strerror() не безопасная функция. Во-первых, возвращаемая ею строка не является константной. При этом она может храниться в статической или в динамической памяти в зависимости от реализации. В первом случае её изменение приведёт к ошибке времени выполнения. Во-вторых, если вы решите сохранить указатель на строку, и после вызовите функцию с новым кодом, все прежние указатели будут указывать уже на новую строку, ибо она использует один буфер для всех строк. В-третьих, её поведение в многопоточной среде не определено в стандарте. Впрочем, в QNX она объявлена как thread safe.
Поэтому в новом стандарте ISO C11 были предложены две очень полезные функции.
size_t strerrorlen_s(errno_t errnum);
Возвращает длину строки с описанием ошибки errnum.
errno_t strerror_s(char *buf, rsize_t buflen, errno_t errnum);
Копирует строку с описание ошибки errnum в буфер buf длиной buflen.
Пример:
/*
// main.c
// strerror_s example
//
// Created by Ariel Feinerman on 23/02/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, const char * argv[])
{
// Generate unique filename.
char *file_name = tmpnam((char[L_tmpnam]){0});
errno = 0;
FILE *file = fopen(file_name, "rb");
// Save error number.
errno_t error_num = errno;
if (file) {
// Do something useful.
fclose(file);
}
else {
#ifdef __STDC_LIB_EXT1__
size_t error_len = strerrorlen_s(errno) + 1;
char error_buf[error_len];
strerror_s(error_buf, error_len, errno);
fprintf(stderr, "Error message : %sn", error_buf);
#endif
}
return EXIT_SUCCESS;
}
Функции входят в Annex K (Bounds-checking interfaces), вызвавший много споров. Он не обязателен к выполнению и целиком не реализован ни в одной из свободных библиотек. Open Watcom C/C++ (Windows), Slibc (GNU libc) и Safe C Library (POSIX), в последней, к сожалению, именно эти две функции не реализованы. Тем не менее, их можно найти в коммерческих средах разработки и системах реального времени, Embarcadero RAD Studio, INtime RTOS, QNX.
Стандарт POSIX.1-2008 определяет следующие функции:
char *strerror_l(int errnum, locale_t locale);
Возвращает строку, содержащую локализованное описание ошибки errnum, используя locale. Безопасна в многопоточной среде. Не реализована в Mac OS X, FreeBSD, NetBSD, OpenBSD, Solaris и прочих коммерческих UNIX. Реализована в Linux, MINIX 3 и Illumos (OpenSolaris).
Пример:
/*
// main.c
// strerror_l example – works on Linux, MINIX 3, Illumos
//
// Created by Ariel Feinerman on 23/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <locale.h>
int main(int argc, const char * argv[])
{
locale_t locale = newlocale(LC_ALL_MASK, "fr_FR.UTF-8", (locale_t) 0);
if (!locale) {
fprintf(stderr, "Error: cannot create locale.");
exit(EXIT_FAILURE);
}
// Generate unique filename.
char *file_name = tmpnam((char[L_tmpnam]){0});
errno = 0;
FILE *file = fopen(tmpnam(file_name, "rb");
// Save error number.
errno_t error_num = errno;
if (file) {
// Do something useful.
fclose(file);
}
else {
char *error_buf = strerror_l(errno, locale);
fprintf(stderr, "Error message : %sn", error_buf);
}
freelocale(locale);
return EXIT_SUCCESS;
}
Вывод:
Error message : Aucun fichier ou dossier de ce type
int strerror_r(int errnum, char *buf, size_t buflen);
Копирует строку с описание ошибки errnum в буфер buf длиной buflen. Если buflen меньше длины строки, лишнее обрезается. Безопасна в многоготочной среде. Реализована во всех UNIX.
Пример:
/*
// main.c
// strerror_r POSIX example
//
// Created by Ariel Feinerman on 25/02/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MSG_LEN 1024
int main(int argc, const char * argv[])
{
// Generate unique filename.
char *file_name = tmpnam((char[L_tmpnam]){0});
errno = 0;
FILE *file = fopen(file_name, "rb");
// Save error number.
errno_t error_num = errno;
if (file) {
// Do something useful.
fclose(file);
}
else {
char error_buf[MSG_LEN];
errno_t error = strerror_r (error_num, error_buf, MSG_LEN);
switch (error) {
case EINVAL:
fprintf (stderr, "strerror_r() failed: invalid error code, %dn", error);
break;
case ERANGE:
fprintf (stderr, "strerror_r() failed: buffer too small: %dn", MSG_LEN);
case 0:
fprintf(stderr, "Error message : %sn", error_buf);
break;
default:
fprintf (stderr, "strerror_r() failed: unknown error, %dn", error);
break;
}
}
return EXIT_SUCCESS;
}
Увы, никакого аналога strerrorlen_s() в POSIX не определили, поэтому длину строки можно выяснить лишь экспериментальным путём. Обычно 300 символов хватает за глаза. GNU C Library в реализации strerror() использует буфер длиной в 1024 символа. Но мало ли, а вдруг?
Пример:
/*
// main.c
// strerror_r safe POSIX example
//
// Created by Ariel Feinerman on 23/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MSG_LEN 1024
#define MUL_FACTOR 2
int main(int argc, const char * argv[])
{
// Generate unique filename.
char *file_name = tmpnam((char[L_tmpnam]){0});
errno = 0;
FILE *file = fopen(file_name, "rb");
// Save error number.
errno_t error_num = errno;
if (file) {
// Do something useful.
fclose(file);
}
else {
errno_t error = 0;
size_t error_len = MSG_LEN;
do {
char error_buf[error_len];
error = strerror_r (error_num, error_buf, error_len);
switch (error) {
case 0:
fprintf(stderr, "File : %snLine : %dnCurrent function : %s()nFailed function : %s()nError message : %sn", __FILE__, __LINE__, __func__, "fopen", error_buf);
break;
case ERANGE:
error_len *= MUL_FACTOR;
break;
case EINVAL:
fprintf (stderr, "strerror_r() failed: invalid error code, %dn", error_num);
break;
default:
fprintf (stderr, "strerror_r() failed: unknown error, %dn", error);
break;
}
} while (error == ERANGE);
}
return EXIT_SUCCESS;
}
Вывод:
File : /Users/ariel/main.c
Line : 47
Current function : main()
Failed function : fopen()
Error message : No such file or directory
Макрос assert()
<assert.h>
void assert(expression)
Макрос, проверяющий условие expression (его результат должен быть числом) во время выполнения. Если условие не выполняется (expression равно нулю), он печатает в stderr значения __FILE__, __LINE__, __func__ и expression в виде строки, после чего вызывает функцию abort().
/*
// main.c
// assert example
//
// Created by Ariel Feinerman on 23/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
int main(int argc, const char * argv[]) {
double x = -1.0;
assert(x >= 0.0);
printf("sqrt(x) = %fn", sqrt(x));
return EXIT_SUCCESS;
}
Вывод:
Assertion failed: (x >= 0.0), function main, file /Users/ariel/main.c, line 17.
Если макрос NDEBUG определён перед включением <assert.h>, то assert() разворачивается в ((void) 0) и не делает ничего. Используется в отладочных целях.
Пример:
/*
// main.c
// assert_example
//
// Created by Ariel Feinerman on 23/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#NDEBUG
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
int main(int argc, const char * argv[]) {
double x = -1.0;
assert(x >= 0.0);
printf("sqrt(x) = %fn", sqrt(x));
return EXIT_SUCCESS;
}
Вывод:
sqrt(x) = nan
Функции atexit(), exit() и abort()
<stdlib.h>
int atexit(void (*func)(void));
Регистрирует функции, вызываемые при нормальном завершении работы программы в порядке, обратном их регистрации. Можно зарегистрировать до 32 функций.
_Noreturn void exit(int exit_code);
Вызывает нормальное завершение программы, возвращает в среду число exit_code. ISO C стандарт определяет всего три возможных значения: 0, EXIT_SUCCESS и EXIT_FAILURE. При этом вызываются функции, зарегистрированные через atexit(), сбрасываются и закрываются потоки ввода — вывода, уничтожаются временные файлы, после чего управление передаётся в среду. Функция exit() вызывается в main() при выполнении return или достижении конца программы.
Главное преимущество exit() в том, что она позволяет завершить программу не только из main(), но и из любой вложенной функции. К примеру, если в глубоко вложенной функции выполнилось (или не выполнилось) некоторое условие, после чего дальнейшее выполнение программы теряет всякий смысл. Подобный приём (early exit) широко используется при написании демонов, системных утилит и парсеров. В интерактивных программах с бесконечным главным циклом exit() можно использовать для выхода из программы при выборе нужного пункта меню.
Пример:
/*
// main.c
// exit example
//
// Created by Ariel Feinerman on 17/03/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void third_2(void)
{
printf("third #2n"); // Does not print.
}
void third_1(void)
{
printf("third #1n"); // Does not print.
}
void second(double num)
{
printf("second : before exit()n"); // Prints.
if ((num < 1.0f) && (num > -1.0f)) {
printf("asin(%.1f) = %.3fn", num, asin(num));
exit(EXIT_SUCCESS);
}
else {
fprintf(stderr, "Error: %.1f is beyond the range [-1.0; 1.0]n", num);
exit(EXIT_FAILURE);
}
printf("second : after exit()n"); // Does not print.
}
void first(double num)
{
printf("first : before second()n")
second(num);
printf("first : after second()n"); // Does not print.
}
int main(int argc, const char * argv[])
{
atexit(third_1); // Register first handler.
atexit(third_2); // Register second handler.
first(-3.0f);
return EXIT_SUCCESS;
}
Вывод:
first : before second()
second : before exit()
Error: -3.0 is beyond the range [-1.0; 1.0]
third #2
third #1
_Noreturn void abort(void);
Вызывает аварийное завершение программы, если сигнал не был перехвачен обработчиком сигналов. Временные файлы не уничтожаются, закрытие потоков определяется реализацией. Самое главное отличие вызовов abort() и exit(EXIT_FAILURE) в том, что первый посылает программе сигнал SIGABRT, его можно перехватить и произвести нужные действия перед завершением программы. Записывается дамп памяти программы (core dump file), если они разрешены. При запуске в отладчике он перехватывает сигнал SIGABRT и останавливает выполнение программы, что очень удобно в отладке.
Пример:
/*
// main.c
// abort example
//
// Created by Ariel Feinerman on 17/02/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void third_2(void)
{
printf("third #2n"); // Does not print.
}
void third_1(void)
{
printf("third #1n"); // Does not print.
}
void second(double num)
{
printf("second : before exit()n"); // Prints.
if ((num < 1.0f) && (num > -1.0f)) {
printf("asin(%.1f) = %.3fn", num, asin(num));
exit(EXIT_SUCCESS);
}
else {
fprintf(stderr, "Error: %.1f is beyond the range [-1.0; 1.0]n", num);
abort();
}
printf("second : after exit()n"); // Does not print.
}
void first(double num)
{
printf("first : before second()n");
second(num);
printf("first : after second()n"); // Does not print.
}
int main(int argc, const char * argv[])
{
atexit(third_1); // register first handler
atexit(third_2); // register second handler
first(-3.0f);
return EXIT_SUCCESS;
}
Вывод:
first : before second()
second : before exit()
Error: -3.0 is beyond the range [-1.0; 1.0]
Abort trap: 6
Вывод в отладчике:
$ lldb abort_example
(lldb) target create "abort_example"
Current executable set to 'abort_example' (x86_64).
(lldb) run
Process 22570 launched: '/Users/ariel/abort_example' (x86_64)
first : before second()
second : before exit()
Error: -3.0 is beyond the range [-1.0; 1.0]
Process 22570 stopped
* thread #1: tid = 0x113a8, 0x00007fff89c01286 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
frame #0: 0x00007fff89c01286 libsystem_kernel.dylib`__pthread_kill + 10
libsystem_kernel.dylib`__pthread_kill:
-> 0x7fff89c01286 <+10>: jae 0x7fff89c01290 ; <+20>
0x7fff89c01288 <+12>: movq %rax, %rdi
0x7fff89c0128b <+15>: jmp 0x7fff89bfcc53 ; cerror_nocancel
0x7fff89c01290 <+20>: retq
(lldb)
В случае критической ошибки нужно использовать функцию abort(). К примеру, если при выделении памяти или записи файла произошла ошибка. Любые дальнейшие действия могут усугубить ситуацию. Если завершить выполнение обычным способом, при котором производится сброс потоков ввода — вывода, можно потерять ещё неповрежденные данные и временные файлы, поэтому самым лучшим решением будет записать дамп и мгновенно завершить программу.
В случае же некритической ошибки, например, вы не смогли открыть файл, можно безопасно выйти через exit().
Функции setjmp() и longjmp()
Вот мы и подошли к самому интересному – функциям нелокальных переходов. setjmp() и longjmp() работают по принципу goto, но в отличие от него позволяют перепрыгивать из одного места в другое в пределах всей программы, а не одной функции.
<setjmp.h>
int setjmp(jmp_buf env);
Сохраняет информацию о контексте выполнения программы (регистры микропроцессора и прочее) в env. Возвращает 0, если была вызвана напрямую или value, если из longjmp().
void longjmp(jmp_buf env, int value);
Восстанавливает контекст выполнения программы из env, возвращает управление setjmp() и передаёт ей value.
Пример:
/*
// main.c
// setjmp simple
//
// Created by Ariel Feinerman on 18/02/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void)
{
printf("second : before longjmp()n"); // prints
longjmp(buf, 1); // jumps back to where setjmp was called – making setjmp now return 1
printf("second : after longjmp()n"); // does not prints
// <- Here is the point that is never reached. All impossible cases like your own house in Miami, your million dollars, your nice girl, etc.
}
void first(void)
{
printf("first : before second()n");
second();
printf("first : after second()n"); // does not print
}
int main(int argc, const char * argv[])
{
if (!setjmp(buf))
first(); // when executed, setjmp returned 0
else // when longjmp jumps back, setjmp returns 1
printf("mainn"); // prints
return EXIT_SUCCESS;
}
Вывод:
first : before second()
second : before longjmp()
main
Используя setjmp() и longjmp() можно реализовать механизм исключений. Во многих языках высокого уровня (например, в Perl) исключения реализованы через них.
Пример:
/*
// main.c
// exception simple
//
// Created by Ariel Feinerman on 18/02/17.
// Copyright 2017 Feinerman Research, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <setjmp.h>
#define str(s) #s
static jmp_buf buf;
typedef enum {
NO_EXCEPTION = 0,
RANGE_EXCEPTION = 1,
NUM_EXCEPTIONS
} exception_t;
static char *exception_name[NUM_EXCEPTIONS] = {
str(NO_EXCEPTION),
str(RANGE_EXCEPTION)
};
float asin_e(float num)
{
if ((num < 1.0f) && (num > -1.0f)) {
return asinf(num);
}
else {
longjmp(buf, RANGE_EXCEPTION); // | @throw
}
}
void do_work(float num)
{
float res = asin_e(num);
printf("asin(%f) = %fn", num, res);
}
int main(int argc, const char * argv[])
{
exception_t exc = NO_EXCEPTION;
if (!(exc = setjmp(buf))) { // |
do_work(-3.0f); // | @try
} // |
else { // |
fprintf(stderr, "%s was hadled in %s()n", exception_name[exc], __func__); // | @catch
} // |
return EXIT_SUCCESS;
}
Вывод:
RANGE_EXCEPTION was hadled in main()
Внимание! Функции setjmp() и longjmp() в первую очередь применяются в системном программировании, и их использование в клиентском коде не рекомендуется. Их применение ухудшает читаемость программы и может привести к непредсказуемым ошибкам. Например, что произойдёт, если вы прыгните не вверх по стеку – в вызывающую функцию, а в параллельную, уже завершившую выполнение?
Информация
- стандарт ISO/IEC C (89/99/11)
- Single UNIX Specifcation, Version 4, 2016 Edition
- The Open Group Base Specifcations Issue 7, 2016 Edition (POSIX.1-2008)
- SEI CERT C Coding Standard
- cправочная информация среды программирования
- справочная информация операционной системы (man pages)
- заголовочные файлы (/usr/include)
- исходные тексты библиотеки (C Standard Library)
| 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.
errno.h — Man Page
system error numbers
Prolog
This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
Synopsis
#include <errno.h>
Description
Some of the functionality described on this reference page extends the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2017 defers to the ISO C standard.
The ISO C standard only requires the symbols [EDOM], [EILSEQ], and [ERANGE] to be defined.
The <errno.h> header shall provide a declaration or definition for errno. The symbol errno shall expand to a modifiable lvalue of type int. It is unspecified whether errno is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name errno, the behavior is undefined.
The <errno.h> header shall define the following macros which shall expand to integer constant expressions with type int, distinct positive values (except as noted below), and which shall be suitable for use in #if preprocessing directives:
- E2BIG
-
Argument list too long.
- EACCES
-
Permission denied.
- EADDRINUSE
-
Address in use.
- EADDRNOTAVAIL
-
Address not available.
- EAFNOSUPPORT
-
Address family not supported.
- EAGAIN
-
Resource unavailable, try again (may be the same value as [EWOULDBLOCK]).
- EALREADY
-
Connection already in progress.
- EBADF
-
Bad file descriptor.
- EBADMSG
-
Bad message.
- EBUSY
-
Device or resource busy.
- ECANCELED
-
Operation canceled.
- ECHILD
-
No child processes.
- ECONNABORTED
-
Connection aborted.
- ECONNREFUSED
-
Connection refused.
- ECONNRESET
-
Connection reset.
- EDEADLK
-
Resource deadlock would occur.
- EDESTADDRREQ
-
Destination address required.
- EDOM
-
Mathematics argument out of domain of function.
- EDQUOT
-
Reserved.
- EEXIST
-
File exists.
- EFAULT
-
Bad address.
- EFBIG
-
File too large.
- EHOSTUNREACH
-
Host is unreachable.
- EIDRM
-
Identifier removed.
- EILSEQ
-
Illegal byte sequence.
- EINPROGRESS
-
Operation in progress.
- EINTR
-
Interrupted function.
- EINVAL
-
Invalid argument.
- EIO
-
I/O error.
- EISCONN
-
Socket is connected.
- EISDIR
-
Is a directory.
- ELOOP
-
Too many levels of symbolic links.
- EMFILE
-
File descriptor value too large.
- EMLINK
-
Too many links.
- EMSGSIZE
-
Message too large.
- EMULTIHOP
-
Reserved.
- ENAMETOOLONG
-
Filename too long.
- ENETDOWN
-
Network is down.
- ENETRESET
-
Connection aborted by network.
- ENETUNREACH
-
Network unreachable.
- ENFILE
-
Too many files open in system.
- ENOBUFS
-
No buffer space available.
- ENODATA
-
No message is available on the STREAM head read queue.
- ENODEV
-
No such device.
- ENOENT
-
No such file or directory.
- ENOEXEC
-
Executable file format error.
- ENOLCK
-
No locks available.
- ENOLINK
-
Reserved.
- ENOMEM
-
Not enough space.
- ENOMSG
-
No message of the desired type.
- ENOPROTOOPT
-
Protocol not available.
- ENOSPC
-
No space left on device.
- ENOSR
-
No STREAM resources.
- ENOSTR
-
Not a STREAM.
- ENOSYS
-
Functionality not supported.
- ENOTCONN
-
The socket is not connected.
- ENOTDIR
-
Not a directory or a symbolic link to a directory.
- ENOTEMPTY
-
Directory not empty.
- ENOTRECOVERABLE
-
State not recoverable.
- ENOTSOCK
-
Not a socket.
- ENOTSUP
-
Not supported (may be the same value as [EOPNOTSUPP]).
- ENOTTY
-
Inappropriate I/O control operation.
- ENXIO
-
No such device or address.
- EOPNOTSUPP
-
Operation not supported on socket (may be the same value as [ENOTSUP]).
- EOVERFLOW
-
Value too large to be stored in data type.
- EOWNERDEAD
-
Previous owner died.
- EPERM
-
Operation not permitted.
- EPIPE
-
Broken pipe.
- EPROTO
-
Protocol error.
- EPROTONOSUPPORT
-
Protocol not supported.
- EPROTOTYPE
-
Protocol wrong type for socket.
- ERANGE
-
Result too large.
- EROFS
-
Read-only file system.
- ESPIPE
-
Invalid seek.
- ESRCH
-
No such process.
- ESTALE
-
Reserved.
- ETIME
-
Stream ioctl() timeout.
- ETIMEDOUT
-
Connection timed out.
- ETXTBSY
-
Text file busy.
- EWOULDBLOCK
-
Operation would block (may be the same value as [EAGAIN]).
- EXDEV
-
Cross-device link.
The following sections are informative.
Application Usage
Additional error numbers may be defined on conforming systems; see the System Interfaces volume of POSIX.1-2017.
Rationale
None.
Future Directions
None.
See Also
The System Interfaces volume of POSIX.1-2017, Section 2.3, Error Numbers
Copyright
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology — Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
Referenced By
errno(3p), signal.h(0p).
2017 IEEE/The Open Group POSIX Programmer’s Manual
������������� ������� ��������� ��������� ���������� (man-��)
errno (3)
NAME
errno - 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 non-zero; 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 non-zero 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)
- 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)
- 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)
- 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
EOPNOTSUPPhave 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 file system (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 file systems
- 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.
SEE ALSO
err(3),
error(3),
perror(3),
strerror(3)
COLOPHON
This page is part of release 3.14 of the Linux
man-pages
project.
A description of the project,
and information about reporting bugs,
can be found at
http://www.kernel.org/doc/man-pages/.
Index
- NAME
- SYNOPSIS
- DESCRIPTION
- NOTES
- SEE ALSO
- COLOPHON

