Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set errno value?

I have two calls to two different methods :

void func1()  {   // do something    if (fail)    {     // then set errno to EEXIST    }  } 

And the second method :

void func2()  {   // do something    if (fail)    {     // then set errno to ENOENT    }  } 
  1. When I set the errno to some value , what does it do ? just error checking ?

  2. How can I set errno in the above methods func1 and func2 to EEXIST and ENOENT

Thanks

like image 756
JAN Avatar asked Jul 28 '12 08:07

JAN


People also ask

How does errno get set?

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.

How do I get 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.

Do I need to set errno to 0?

To detect an error, an application must set errno to 0 before calling the function and check whether it is nonzero after the call. Affected functions include strcoll() , strxfrm() , strerror() , wcscoll() , wcsxfrm() , and fwide() . The C Standard allows these functions to set errno to a nonzero value on success.

Do you have to reset errno?

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

For all practical purposes, you can treat errno like a global variable (although it's usually not). So include errno.h and just use it:

errno = ENOENT; 

You should ask yourself if errno is the best error-reporting mechanism for your purposes. Can the functions be engineered to return the error code themselves ?

like image 145
cnicutar Avatar answered Sep 20 '22 13:09

cnicutar


IMO, the standard errno designed for system level. My experience is do not pollute them. If you want to simulate the C standard errno mechanism, you can do some definition like:

/* your_errno.c */ __thread int g_your_error_code;  /* your_errno.h */ extern __thread int g_your_error_code #define set_your_errno(err) (g_your_error_code = (err)) #define your_errno (g_your_error_code) 

and also you can still implement your_perror(err_code). More information, please refer to glibc's implementation.

like image 42
coanor Avatar answered Sep 20 '22 13:09

coanor