errno

关于errno有以下需要注意:

1  A common mistake is to do

           if (somecall() == -1) {                printf("somecall() failed\n");                if (errno == ...) { ... }            }

       where errno no longer needs to have the value it had upon return from somecall() (i.e., it may have  been  changed  by  the        printf(3)).  If the value of errno should be preserved across a library call, it must be saved:

           if (somecall() == -1) {                int errsv = errno;                printf("somecall() failed\n");                if (errsv == ...) { ... }            }

       It  was  common in traditional C to declare errno manually (i.e., extern int errno) instead of including <errno.h>.  Do not        do this.  It will not work with modern versions of the C library.  However, on (very) old UNIX systems,  there  may  be  no        <errno.h> and the declaration is needed.

 

2、如果系统调用或库函数正确执行的话,errno的值是不会被清零(置0,注意这里是不会被清零,不是不会被改变)的,假若执行函数A的时候发生了错误errno被改变,接下来直接执行函数B,如果函数B正确执行的话,errno还保留函数A发生错误时被设置的值。所以,在利用errno之前,最好先对函数的返回值进行判断,看是否发生了错误,返回值错误再利用errno判断时哪里发生了错误。所以如果一个函数无法从返回值上判断正误,而只能通过errno来判断出错,那你在调用它之前必须手动将errno清零!

3、系统调用或库函数正确执行,并不保证errno的值不会被改变!

4、任何错误号(即发生错误时errno的取值)都是非0的。

综上所述,当需要用errno来判断函数是否正确执行的时候,最好先将errno清零,函数执行结束时,通过其返回值判断函数是否正确执行,若没有正确执行,再根据errno判断时哪里发生了错误。

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2013-07/87238.htm

posted @ 2015-12-06 16:50  软跋涉者  阅读(267)  评论(0编辑  收藏  举报