Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the maximum errno value?

Tags:

c

errno

I want to build an unique error number, which consists of a random number and the errno of a system call. Example:

#define ERRID(ERRNO) ((uint32_t)rand() << 16 | (uint32_t)(ERRNO) & 0xFFFF)

I need to know how many bits are required to store an errno value.

I know it is defined as int. But the total number of errors is much lower than 9,223,372,036,854,775,807 on a 64 bit system. On my Debian the maximum number seems to be 529.

dpkg -L linux-headers-3.16.0-4-common|
grep errno.h|
xargs cat|
awk '/^#define/{print $3}'|
sort -rn|
head -1
529

So uint16_t seems to be enough to store the errno.

But how to be sure? How can I find out how many errnos the operating system actually uses? Is it documented anywhere?

like image 704
ceving Avatar asked Oct 28 '25 06:10

ceving


2 Answers

There is no portable way to do this. POSIX (and C) allows the implementation to use all positive int values as error numbers, there is no constant for the maximum number used, and there may not be an integer type larger than int.

like image 169
dpi Avatar answered Oct 29 '25 21:10

dpi


You can just pass around a handle instead which contains both the errno error code and the random identifier (I assume you want this to be a unique ID in order to be able to identify specific instances of errors later…?)

struct ErrorID {
    int errno_error;
    int rand_id;
}

ErrorID this_func_can_fail()
{
    return (ErrorID){ .errno_error = errno, .rand_id = rand() };
}

This compiles:

#include <errno.h>
#include <stdlib.h>

struct ErrorID {
    int errno_error;
    int rand_id;
};

struct ErrorID this_func_can_fail()
{
    return (struct ErrorID){ .errno_error = errno, .rand_id = rand() };
}

int main (int argc, char *argv[])
{
  this_func_can_fail();
  return 0;
}
like image 41
The Paramagnetic Croissant Avatar answered Oct 29 '25 21:10

The Paramagnetic Croissant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!