2012-07-09 44 views
1

在我的代码open()失败,返回代码-1,但不知何故errno没有得到设置。为什么open()失败并且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 

为什么错误号没有被设置?我如何确定为什么open()失败?

回答

10
int errno=0; 

问题是你重新声明errno,从而遮蔽全局符号(它甚至不需要一个普通的变量)。效果是什么open设置和你打印什么是不同的东西。相反,你应该包括标准errno.h

+2

此外,不要'errno = 0'。无论如何,open都会正确设置它。 – ArjunShankar 2012-07-09 14:07:39

+0

和这个open()是做什么的? – 2012-07-09 14:08:26

+1

@ Mr.32这个公开调用似乎是直接打开一个'tty'设备,通常与控制台相关联。我怀疑错误信息是EPERM。 – cnicutar 2012-07-09 14:09:09

2

你不应该自己定义errno变量。 errno它是errno.h中定义的全局变量(它比varibale更复杂)因此,删除你int errno = 0;并再次运行。不要忘了包括errno.h中

1

请添加到您的模块:中#include <errno.h> 代替int errno;

1

你声明一个局部变量errno,有效地屏蔽了全球errno。您需要包括errno.h,并宣布将extern错误号,例如:

#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()打开错误号的整数转换为人类可读的错误消息。你需要包括string.h那个:

#include <errno.h> 
#include <string.h> 

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