为什么 printf() 在 sleep() 之前不打印任何内容? [英] Why does printf() not print anything before sleep()?

查看:61
本文介绍了为什么 printf() 在 sleep() 之前不打印任何内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 Kernighan 和 Ritchie 的书学习 C;我在第四章(函数的东西)的基础知识.前几天我开始对 sleep() 函数感到好奇,所以试着像这样使用它:

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;
}

问题在于程序的输出,看起来它先执行sleep(),然后执行printf(),换句话说,它等待五个秒,然后打印字符串.所以我想,也许程序进入 sleep() 如此之快以至于它不会让 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.

如何显示字符串然后让程序进入睡眠状态?编译器是 OpenBSD 4.3 中的 GCC 3.3.5 (propolice).

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 我不知道你是如何正确地把预处理器行放在这里的.

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

推荐答案

printf() 写入stdout(默认输出流),通常是行缓冲的.缓冲区在 sleep 被调用时没有被刷新,所以没有显示任何内容,当程序退出时,所有流都会自动刷新,这就是它在退出之前打印的原因.打印换行符通常会导致流被刷新,或者您可以使用 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;
}

如果您要打印到非行缓冲的流,例如 stdout 被重定向或您正在写入文件,那么简单地打印换行符可能不起作用.在这种情况下,如果您希望立即写入数据,则应使用 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() 在 sleep() 之前不打印任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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