热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

运行在while循环中的代码期望输出-codesleepinginwhileloopexpecttheoutput

#include<stdio.h>#include<unistd.h>intmain(){while(1){fprintf(s
#include 
#include 
int main()
{
    while(1)
    {
        fprintf(stdout,"hello-out");
        fprintf(stderr,"hello-err");
        sleep(1);
    }
    return 0;
}

The output of above on my machine is

上面在我的机器上的输出是

hello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-err

I had to kill the program to stop it. Is it the correct and expected behavior. Or it is wrong.This was an interview question hence I am posting here.

我不得不终止程序以阻止它。这是正确的和预期的行为。或者它是错误的。这是一个面试问题,因此我在这里发布。

3 个解决方案

#1


8  

This is the expected output:

这是预期输出:

  • The program loops forever because of the while (1) loop.
  • 由于while(1)循环,程序将永远循环。
  • stdout is line-buffered (by default), so it only flushes to the console when a new-line character ('\n') is printed. As you aren't printing any new-line characters, you never see any of the hello-out text.
  • stdout是行缓冲的(默认情况下),因此只有在打印了新行字符('\n')时才会刷新到控制台。因为您没有打印任何新行字符,所以您永远不会看到任何helloout文本。
  • However stderr is not line-buffered (by default), so it updates the console on every new fprintf() call.
  • 但是stderr不是行缓冲的(默认情况下),所以它在每个新的fprintf()调用上更新控制台。

#2


5  

stdout is buffered on most machines. You won't see any output from any fprintf calls to stdout unless you print a newline or call fflush().

stdout在大多数机器上都有缓冲。除非您打印一个换行符或调用fflush(),否则不会看到来自任何fprintf调用stdout的输出。

So yes, it's expected behaviour, most of the time.

是的,大多数时候是预期行为。

#3


4  

While everyone is right that you have an infinite loop, stderr is not buffered so you get it immediately, stdout is line buffered so it is deferred until you get a newline, they do not mention that stdout does not have infinite storage. I think the buffers are 1k or so by default (see setbuf). If you wait long enough you will get a very long burst of hello-out sequences. It is entirely possible that the last hello-out might be truncated part of the way through the string "hello-out".

虽然每个人都认为你有一个无限循环,但是stderr并没有缓冲,所以你马上就能得到它,stdout是行缓冲的,所以它被延迟,直到你得到一个换行符,他们没有提到stdout没有无限的存储空间。我认为默认的缓冲区是1k左右(参见setbuf)。如果你等待的时间足够长,你将会得到一长串hello-out序列。完全有可能最后的helloout通过字符串“helloout”被截断。

[...]hello-outhello-outhellhello-errhello-err
                       ^^^^

推荐阅读
author-avatar
大帅哥明日夜
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有