Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print errno as mnemonic?

Tags:

c

linux

I have seen Symbolic errno to String - Stack Overflow, so even if that question is bash related, I can already tell that this isn't trivial; but just to confirm:

Is there a C API function, which like strerror() will accept the numeric errno as argument - but which will print the mnemonic (e.g. EINVAL) instead of the error description string (e.g. "Invalid argument")?

As an example, I'd like

printf("Number: %d (%s): '%s'\n", 22, strerror_mnemonic(22), strerror(22) );

... to print:

Number: 22 (EINVAL): 'Invalid argument'

... where strerror_mnemonic is pseudocode for the C function I'm looking for.

like image 765
sdaau Avatar asked Feb 24 '14 17:02

sdaau


People also ask

How to print errno value?

Your program can use the strerror() and perror() functions to print the value of errno. The strerror() function returns a pointer to an error message string that is associated with errno. The perror() function prints a message to stderr.

Can errno modify?

errno The value in errno 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. The value of errno is never set to zero by any system call or library function.

Does errno get reset?

Initializing Errno Your program should always initialize errno to 0 (zero) before calling a function because errno is not reset by any library functions. Check for the value of errno immediately after calling the function that you want to check. You should also initialize errno to zero after an error has occurred.


2 Answers

The second part of your question is answered by strerror (as you point out), or better strerror_r, but in glibc at least you can simply use %m as a format specifier.

The first part is more interesting, i.e. how do you get the name of the C constant for the error. I believe there is no way to do that using standard glibc. You could construct your own static array or hash table to do this relatively easily.

like image 108
abligh Avatar answered Oct 23 '22 04:10

abligh


Unfortunately not; there is no introspection support for the E error macros.

You can do this trivially in Python:

import errno
print(errno.errorcode[errno.EPERM])

This is because the Python maintainers have gone to the trouble of generating a lookup table: http://hg.python.org/cpython/file/tip/Modules/errnomodule.c

like image 2
ecatmur Avatar answered Oct 23 '22 03:10

ecatmur