为什么open()失败时errno没有设置?

3
在我的代码中,open() 返回-1,但一些原因导致errno 没有被设置。
int fd;
int errno=0;
fd = open("/dev/tty0", O_RDWR | O_SYNC);
printf("errno is %d and fd is %d",errno,fd);

输出结果为:

errno is 0 and fd is -1

为什么 errno 没有被设置?我该如何确定 open() 失败的原因?

4个回答

15
int errno=0;
问题在于你重新声明了errno,从而遮蔽了全局符号(它甚至不一定是普通变量)。影响是open设置的内容和你打印的内容是不同的。相反,你应该包含标准的errno.h头文件。

3
不要执行 errno = 0open 函数本身会正确设置它。 - ArjunShankar
1
@Mr.32 那个开放调用似乎直接打开了一个tty设备,通常与控制台相关联。我怀疑错误消息是EPERM。 - cnicutar

3

您不应该自行定义errno变量。 errno是全局变量(实际上比变量更复杂),定义在errno.h中。因此,请删除int errno = 0;并重新运行。不要忘记包含errno.h。


3

您正在声明一个本地的errno变量,实际上掩盖了全局的errno。您需要包含errno.h,并声明外部的errno,例如:

#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 ...
}

您也可以使用strerror()将errno整数转换为人类可读的错误消息。您需要包含string.h
#include <errno.h>
#include <string.h>

fprintf( stderr, "Error is %s (errno=%d)\n", strerror( errno ), errno );

1
请将以下代码添加到您的模块中:#include <errno.h>,而不是int errno;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接