1

In c++, I have this code:

#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
  cout<<"before-sleep"<<endl;
  sleep(5);
  cout<<"after-sleep"<<endl;
  return 1;
} 

then i compile it with g++ to main.exe and run it. when run it I redirect the std out to a file :

./main.exe > file.log

however, the two line "before-sleep" and "after-sleep" are print to the file almost at the same time -- all have 5s delay. How can I made the first line print to the file immediately and the second line print to the file with 5s delay?

The situation is the same in python:

import time
print 'before sleep'
time.sleep(5)
print 'after sleep'
spring cc
  • 937
  • 1
  • 10
  • 19
  • 1
    try `cout.flush();` just before `sleep(5);` – Logman Nov 13 '16 at 00:32
  • This is entirely a buffering issue. Note that `endl` flushes the buffer in c++, so I suspect the problem is buffering in the shell redirection. Might want to look at [this](http://stackoverflow.com/questions/11337041/force-line-buffering-of-stdout-when-piping-to-tee). For Python, you'll need to add an `sys.stdout.flush()` after the first print. – Alec Nov 13 '16 at 00:33
  • @Logman `endl` is special: it both outputs out a newline and flushes. – Alec Nov 13 '16 at 00:34
  • @Alec endl should flush buffer but in my experience on some systems I encountered it doesn't. – Logman Nov 13 '16 at 00:37
  • both the cout.flush() and sys.stdout.fush() doesn't work respectvely in c++ and python, does it works in your computer ?@Alec @Logman – spring cc Nov 13 '16 at 01:48
  • Yes it works on my computer. As Alec said it probably something with IO buffers or your test has error. Try using `tail -f file.log` to confirmed your test is valid. – Logman Nov 13 '16 at 05:01

0 Answers0