2012-07-09 42 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); 
相關問題