Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22006

C program still misses some output after flushing IO buffer

$
0
0

The following C program misses some output even after flushing the IO buffer.

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

void fork2() {
    printf("(L0 %d) ", getpid());
    fflush(stdout);
    fork();
    printf("(L1 %d) ", getpid());
    fflush(stdout);
    fork();
    printf("(Bye %d) ", getpid());
    fflush(stdout);
}

int main() {
    printf("parent: %d\n", getpid());
    fflush(stdout);
    fork2();
    fflush(stdout);
    return 0;
}

The expected output of the above program is like the following, which has 7 tuples.

parent: 26874
(L0 26874) (L1 26874) (Bye 26874) (L1 26875) (Bye 26876) (Bye 26875) (Bye 26877)

However, I run it multiple times. Its output is not always like this. Sometimes it misses part of the output at the end like following, which contains less than 7 tuples.

parent: 26882
(L0 26882) (L1 26882) (Bye 26882) (L1 26883) (Bye 26884) (Bye 26883)

Why the program misses some output even after flushing the IO buffer?

Won't the program flush IO buffer automatically before exit?

[UPDATE]

This sreenshot shows my shell when I run multiple times continuously.

screenshot

But my another machine acts in a different way like following.

enter image description here


Viewing all articles
Browse latest Browse all 22006

Trending Articles