LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-26-2004, 04:52 AM   #1
blackzone
Member
 
Registered: Jun 2004
Posts: 256

Rep: Reputation: 30
io related question, when printf is called


I sometimes got printf() called at unexpected time.
For example for the program below I would expect output of "0" wait 5 second than a "1"

But I got wait 5 second and "01" print at the same time.

Can give more insite of why this happened? Believe it have something to do with buffer?

---------------------------------------------------------------------------------------
int main(){
int i=0;
printf("%d", i);

sleep(5)

i++;
printf("%d, i);
}
 
Old 07-26-2004, 05:37 AM   #2
Vookimedlo
Member
 
Registered: Jul 2004
Location: Czech Republic - Roudnice nad Labem
Distribution: Debian
Posts: 253

Rep: Reputation: 34
It's normal, standard output is buffered, but standard error output isn't.

For error outputs use stderr streams.

But if you want to use normal output, you should always invoke fflush(FILE*)

for example:
Code:
#include <stdio.h>

int main (int argc, char **argv)
{
  int i=0;
  printf("%d", i);
  fflush(stdout);

  sleep(5);    
  i++;
  printf("%d", i);

  return 0;
}
 
Old 07-26-2004, 05:41 AM   #3
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Rep: Reputation: 30
use this one instead:
Code:
int main(){
  int i=0;
  printf("%d", i);
  fflush (stdout); // force output buffer to be displayed!
  sleep(5);
  i++;
  printf("%d, i);
}
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
c printf question. fredgt Programming 5 09-09-2004 05:06 AM
c related question. blackzone Programming 1 07-24-2004 08:55 AM
What's it called? Terminal? Concole? Command Line? It's a stupit question, I know. brynjarh Linux - Newbie 4 07-11-2004 02:09 AM
Simple printf question AMMullan Programming 3 02-13-2004 10:12 PM
DNS related question tusher Linux - Newbie 1 12-07-2003 01:03 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:05 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration