In usual case open() return the new file descriptor, or -1 if an error occurred and in that case, errno is set appropriately.
I am not understanding why this mechanism of errno is used here? whats the purpose of here? why just we can not map all error with some negative return no?
like
fd = open("/dev/tty0", O_RDWR | O_SYNC);
if(fd == -1)
printf("this is EACCES error");
else if (fd == -2)
printf("this is EPERM error");
Is there any benifit of errno mechanism.? if yes then i would like to know/understand then in other things i can also use this mechanism.
Since
fopenreturns aFILE*you can’t expect it to return an error code in that pointer: the only “special” value for pointers is0.As you observe, for
openthis restriction doesn’t hold. In fact systems as linux do exactly what you propose in their lower levels. The system call under the hood returns the negative error code if things go wrong. That (negated) code is then plug intoerrnoby a shallow user space wrapper which then returns the-1to indicate the error to the application.The reason that this is done so is purely historical. In good old times there was no threading and
errnowas still just a simple global variable. At that time the chosen strategy incurred not much overhead and probably seemed an acceptable way to communicate between OS and application. Since such interfaces basically can’t be changed without breaking a lot of code, we will be stuck witherrnoas a pseudo variable that is thread local.This is not ideal, but the overhead is not as bad as it sounds, since these are clearly error indications that should occur only exceptionally.