在我的代码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()
失败?
在我的代码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()
失败?
int errno=0;
问题是你重新声明errno
,从而遮蔽全局符号(它甚至不需要一个普通的变量)。效果是什么open
设置和你打印什么是不同的东西。相反,你应该包括标准errno.h
。
你不应该自己定义errno变量。 errno它是errno.h中定义的全局变量(它比varibale更复杂)因此,删除你int errno = 0;
并再次运行。不要忘了包括errno.h中
请添加到您的模块:中#include <errno.h>
代替int errno;
你声明一个局部变量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);
此外,不要'errno = 0'。无论如何,open都会正确设置它。 – ArjunShankar 2012-07-09 14:07:39
和这个open()是做什么的? – 2012-07-09 14:08:26
@ Mr.32这个公开调用似乎是直接打开一个'tty'设备,通常与控制台相关联。我怀疑错误信息是EPERM。 – cnicutar 2012-07-09 14:09:09