Linux c error function

How to know what the ‘errno’ means?

When calling execl(. ) , I get an errno=2 . What does it mean? How can I know the meaning of this errno ?

15 Answers 15

You can use strerror() to get a human-readable string for the error number. This is the same string printed by perror() but it’s useful if you’re formatting the error message for something other than standard error output.

#include #include /* . */ if(read(fd, buf, 1)==-1)

Linux also supports the explicitly-threadsafe variant strerror_r() .

1. It is NOT guaranteed to be reentrant or thread safe 3. Most implementations DO write to internal static buffer, including GNU LibC implementation

@Ivan is correct and @Chris in incorrect. strerror() is not thread safe while strerror_r() is thread safe. MT-Safe or Thread-Safe functions are safe to call in the presence of other threads. MT, in MT-Safe, stands for Multi Thread. -p26, The GNU C Library char * strerror(int errnum ) [Function] Preliminary: | MT-Unsafe race:strerror | AS-Unsafe heap i18n | AC-Unsafe mem | See Section 1.2.2.1 [POSIX Safety Concepts], page 2. -p58, The GNU C Library

Instead of running perror on any error code you get, you can retrieve a complete listing of errno values on your system with the following one-liner:

cpp -dM /usr/include/errno.h | grep ‘define E’ | sort -n -k 3

On Linux there is also a very neat tool that can tell right away what each error code means. On Ubuntu: apt-get install errno .

Then if for example you want to get the description of error type 2, just type errno 2 in the terminal.

With errno -l you get a list with all errors and their descriptions. Much easier that other methods mentioned by previous posters.

Not unless you are doing something odd. Normally, embedding perror / strerror is better because then the USER doesn’t have to look it up. Although, errno -l is better for finding them.

Here is the output from errno -l reformatted for readability:

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

I used tabularise in Vim to align the columns:

:%Tab /^[^ ]*\zs /r1l1l1 :%Tab /^ *[^ ]* *[^ ]*\zs /l1 

Источник

Читайте также:  Все директории find linux

Errno in C

C language does not directly allow error management but it does enable access at a lesser level via return values. In the event of inaccuracy, the majority of C or perhaps even Linux function calls yield -1 or Void and set the errno error code. It’s a universal constant that shows when a function call has failed. In the header file, you’ll find a list of different error codes. As a result, a C developer can examine the supplied values and, based on them, take necessary measures. There seem to be no trouble in the program if the result is 0. Within this article today, we will be discussing the use of the “errno” variable to get error codes and messages on our Linux environment (i.e., Ubuntu 20.0.4 system.) Let’s get started with the opening of a terminal shell in the Ubuntu 20.04 Linux operating system and installing the GCC compiler of C.

Before moving towards the creation of a C code, we need a C file in our Linux system. Thus, we have been using the touch instruction to create one. This file must contain a “c” extension at its end. As you can find out, we have built a file named “errno.c”. The list command has been used to list all the files and folders of our current working directory in Linux. The newly made C file “errno.c” is also listed here. To create C code in the file, we must open it in some editor like a text editor, Vim editor, or Gnu Nano editor. So, we have been opening it inside the GNU Nano editor with the use of the “nano” command in the shell. This file will be opened in a terminal-like editor.

Читайте также:  Minecraft on linux fedora

Example 01

Let’s begin with the initial example of this article. Let’s say, you want to open and read the data from a specific text file residing in the same current directory using the filing in C code. For this, we must use the standard input output library of a C in our code. So, we have included it at the opening line employing the “#include” keyword.

After that, we need to use the “errno.h” header in this C code so that we can utilize the built-in variable “errno” to get the error code and message. The main execution will be started from the “main()” function of the C program. Within this main program, we have been using the “FILE” variable to initialize the file descriptor “f” of pointer type. This file descriptor has been used to open the file “new.txt” in a read-only format using the “fopen” function of filing in C. The if-else statement is here to check whether the file is successfully opened or not. The “if” part of the statement will check if the returned result of the file descriptor is equal to 0 or not. If 0, then it means the file is missing or not opened successfully. Thus, the printf statement will be using the “errno” variable to display the error code.

On the other hand, the “else” part will be utilized when the condition doesn’t satisfy the file descriptor value other than. The printf statement will display that the opening is successful.

We have compiled this code with the “gcc” compiler and then executed it with the “./a.out” instruction. This code execution returns the error code number 2 where no file has been found.

Читайте также:  Служба astra linux directory

To remove this error, we need to create a new text file with the “touch” instruction and add some data to it with the “echo” statement as shown. The “cat” instruction is showing that the file contains the newly added text data in it.

Now, when you compile and run the same code in the shell, it will execute the “else” part and display the message “Successful” (i.e., file got found now.)

If you want to display the error message along with its error code, you need to use the “strerror” function in the program. For that, you need to use the “string.h” header in the code as well. So, we have added the header and updated the “if” component of the “if-else” statement. The strerror() function call has been suing the “errno” to get the error message by its error code.

When your file is missing, you will be displayed with the error message “No such file or directory” at the shell as shown.

Example 02

Let’s check the error number for another error example. We have been using the standard libraries in the program and the main() function contains the initialization of a variable “val” and function call to “check” function by passing it the “val” variable. The check() function would be using the “if-else” statement to check if the value “val” is zero or not and hence the other value can be divisible by it or not. As the value “val” is 7, it can be divisible by 8. So the “else” part of the check() function would be executed to calculate the division result and display it on the shell.

After the compilation and execution, we have found that the division is possible. The else part has calculated and displayed the division value between 89 and value “7” for variable “val”.

Let’s update the code again and add 0 as a value to the variable “val” in the main() function to reverse the results. So, we have updated the “val” value to 0 as indicated in the image below. The remaining the code remained untouched.

After running this updated code, we have the error code 0 and its error message.

Conclusion

This is about the use of the “errno” variable in the article to get the error codes of different exceptions using its “errno.h” header. Also, we have discussed the use of “strerror” function to display the error message along with the code number. We have incorporated two instances in this guide to better explain the idea of errno.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Оцените статью
Adblock
detector