Find the answer to your Linux question:
Results 1 to 4 of 4
Suppose I have code like this int main(){ printf("hello"); sleep(1); printf("hallo\n"); } The result is the "hello" won't come out after one second. So it means it doesn't print until ...
  1. #1
    Just Joined! garry_3peace's Avatar
    Join Date
    Oct 2008
    Posts
    67

    \n in Linux behaviour

    Suppose I have code like this

    int main(){
    printf("hello");
    sleep(1);
    printf("hallo\n");
    }

    The result is the "hello" won't come out after one second. So it means it doesn't print until it meets \n which it appear at "hallo\n". Is this purposely created like this? or a bug?

  2. #2
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    This is a feature. The intention is to avoid actually doing I/O until necessary, thus improving the speed of many programs.

    If you wish to force output after a printf() statement, do this just after that statement:
    Code:
    fflush(stdout);
    If you wish all output to appear on the screen immediately, then instead of doing this:
    Code:
    printf("hello");
    you can do this:
    Code:
    fprintf(stderr,"hello");
    It's understood that stderr data must be seen immediately.

    For more information and flexibility, do this at the command prompt:
    Code:
    man setbuf
    Hope this helps.
    --
    Bill

    Old age and treachery will overcome youth and skill.

  3. #3
    Just Joined! garry_3peace's Avatar
    Join Date
    Oct 2008
    Posts
    67
    So \n beside make newline also flush the standard output like C++ using endl... right ? I understand now. Thanks wje_lf

  4. #4
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    \n beside make newline also flush the standard output
    Yes, but with setbuf() you can change this in one of two ways: you can make it so that with each printf() or fprintf() the buffer will be flushed; or you can make it so that even /n won't flush the buffer, and the buffer won't be flushed until it's full.
    --
    Bill

    Old age and treachery will overcome youth and skill.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...