为什么睡眠()我的printf之前执行(),我的code的顺序相反? [英] Why does sleep() execute before my printf(), the opposite order of my code?

查看:98
本文介绍了为什么睡眠()我的printf之前执行(),我的code的顺序相反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学习Kernighan和Ritchie的书℃;我在第四章的基础知识(函数的东西)。有一天,我成了好奇睡眠()的功能,所以试图用这样的:

I'm just learning C with Kernighan and Ritchie's book; I'm in the basics of the fourth chapter (functions stuff). The other day I became curious about the sleep() function, so tried to use it like this:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
  printf(" I like cows.");
  sleep(5);
  return 0;
}

问题是该程序的输出,它看起来像它的睡眠(),然后启动的printf(),换句话说,它会等待五秒钟,然后打印字符串。所以我想,也许是程序获取到睡眠()如此之快,它不会让的printf()有他做了像我想要的工作,那就是打印字符串,然后睡觉。

The problem is the output of the program, it looks like it does the sleep() first and then the printf(), in other words, it waits five seconds and then prints the string. So I thought, maybe the program gets to sleep() so fast that it doesn't let printf() have his work done like I want, that is print the string and then sleep.

我怎么可以显示字符串,然后把程序睡觉?
编译器GCC是3.3.5(propolice)在OpenBSD的4.3。

How can I show the string and then put the program to sleep? The compiler is GCC 3.3.5 (propolice) in OpenBSD 4.3.

PS我不知道你是怎么把正确这里的preprocessor线。

PS I don't know how you put here the preprocessor lines correctly.

推荐答案

的printf()写入标准输出(缺省输出流)通常是行缓冲。该缓冲区不是由时间刷新睡眠被称为所以未显示任何内容,当程序退出所有流自动刷新这就是为什么它打印退出之前。打印新行通常会导致流被刷新,或者你可以使用 fflush 功能:

printf() writes to stdout (the default output stream) which is usually line buffered. The buffer isn't flushed by the time sleep is called so nothing is displayed, when the program exits all streams are automatically flushed which is why it prints right before exiting. Printing a newline will usually cause the stream to be flushed, alternatively you could use the fflush function:

int main(void)
{
  printf(" I like cows.\n");
  sleep(5);
  return 0;
}

int main(void)
{
  printf(" I like cows.");
  fflush(stdout);
  sleep(5);
  return 0;
}

如果您打印到未行缓冲流,如果标准输出重定向或你正在写一个文件作为可能的情况下,简单的打印一个换行符可能不会工作。在这种情况下,如果你想要的数据立即写入,你应该使用 fflush

If you are printing to a stream that is not line buffered, as may be the case if stdout is redirected or you are writing to a file, simply printing a newline probably won't work. In such cases you should use fflush if you want the data written immediately.

这篇关于为什么睡眠()我的printf之前执行(),我的code的顺序相反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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