为什么errno可以通过scanf设置为零?(输入"ctrl + D"时) [英] Why errno can set to zero by scanf?(when enter "ctrl+D")

查看:45
本文介绍了为什么errno可以通过scanf设置为零?(输入"ctrl + D"时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该手册告诉我们:任何系统调用或库函数都不会将errno设置为零.但是我想知道,为什么在下面的代码中用scanf可以将errno设置为零?(当scanf:输入"ctrl + D"时)

The manual tells us:errno is never set to zero by any system call or library function. But I want to know, Why errno can set to zero by scanf in following codes?(when scanf:enter the"ctrl+D")

#include <stdio.h>
#include <errno.h>
int main()
{
    int i;
    errno = 5;
    printf("errno:%d\n",errno);
    if (scanf("%d", &i) < 1)
        perror("scanf");
    printf("errno:%d\n",errno);
    printf("i:%d\n", i);
    return 0;
}

推荐答案

我可以在 input_error() #define 定义为:

#define input_error()         do {     
                          errval = 1; 
                          if (done == 0) done = EOF;
                          goto errout; 
                        } while (0)

其中 errout 是结尾的清理代码的标签.

where errout is the label for the cleanup code at the end.

因此,在 inchar()调用之前,似乎 errno 被设置为 0 ,后来替换了旧值,保持 errno 不变.但是,如果发生错误并且执行了 if 语句(特别是如果 inchar()的计算结果为 EOF ,则在这种情况下就是这种情况)),则似乎已跳过了将 errno 重置为其原始值的代码.话虽如此,条件只有在 errno == EINTR 且因此不为零的情况下才成立,在这里肯定不是这种情况,因此与该代码无关,但是在这里我只能看到 errno 被设置为 0 .正如注释所暗示的那样, inchar()本身确实与 errno 混为一谈,并且可以将 errno 设置为 inchar_errno ,它在第223行被初始化为 0 ,因此也有可能存在其他一些执行路径,其中 inchar_errno 不会更新,但无论如何都会分配给 errno

So it looks like errno is getting set to 0 prior to the inchar() call, and the old value is later replaced, leaving errno unchanged. But if an error occurs and that if statement executes (notably, if inchar() evaluates to EOF, which is what is happening in this case), it looks like the code to reset errno to its original value may be being skipped. That being said, the condition will only be true if errno == EINTR and therefore not zero, which certainly doesn't appear to be the case, here, so it may have nothing to do with this code, but this is only place I can see errno being set to 0. inchar() itself does mess around with errno, as the comment suggests, and can set errno to inchar_errno, which is initialized to 0 on line 223, so it's also possible there's some other execution path where inchar_errno is not updated but gets assigned to errno anyway.

这篇关于为什么errno可以通过scanf设置为零?(输入"ctrl + D"时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆