Why does open() fail and errno is not set?
Solution 1
int errno=0;
The problem is you redeclared errno
, thereby shadowing the global symbol (which need not even be a plain variable). The effect is that what open
sets and what you're printing are different things. Instead you should include the standard errno.h
.
Solution 2
You shouldn't define errno variable by yourself. errno it is global varibale (aclually it's more complex than just varibale) defined in errno.h So remove you int errno = 0;
and run again. Dont forget to include errno.h
Solution 3
You're declaring a local errno
variable, effectively masking the global errno
. You need to include errno.h
, and declare the extern errno, e.g.:
#include <errno.h>
...
extern int errno;
...
fd = open( "/dev/tty0", O_RDWR | O_SYNC );
if ( fd < 0 ) {
fprintf( stderr, "errno is %d\n", errno );
... error handling goes here ...
}
You can also use strerror()
to turn the errno integer into a human readable error message. You'll need to include string.h
for that:
#include <errno.h>
#include <string.h>
fprintf( stderr, "Error is %s (errno=%d)\n", strerror( errno ), errno );
Solution 4
Please add this to your module: #include <errno.h>
instead of int errno;
Jeegar Patel
Written first piece of code at Age 14 in HTML & pascal Written first piece of code in c programming language at Age 18 in 2007 Professional Embedded Software engineer (Multimedia) since 2011 Worked in Gstreamer, Yocto, OpenMAX OMX-IL, H264, H265 video codec internal, ALSA framework, MKV container format internals, FFMPEG, Linux device driver development, Android porting, Android native app development (JNI interface) Linux application layer programming, Firmware development on various RTOS system like(TI's SYS/BIOS, Qualcomm Hexagon DSP, Custom RTOS on custom microprocessors)
Updated on June 04, 2022Comments
-
Jeegar Patel almost 2 years
In my code
open()
fails with a return code of -1 but somehowerrno
is not getting set.int fd; int errno=0; fd = open("/dev/tty0", O_RDWR | O_SYNC); printf("errno is %d and fd is %d",errno,fd);
output is
errno is 0 and fd is -1
Why is errno not being set? How can i determine why
open()
fails? -
ArjunShankar almost 12 yearsAlso, don't do
errno = 0
.open
will set it correctly anyway. -
cnicutar almost 12 years@Mr.32 That open call seems to be directly opening a
tty
device, typically associated with a console. I suspect the error message is EPERM.