c - Unix system call to print numbers in ascending then descending order -
i have small program needs print numbers in following format:
0 1 2 3 4 3 2 1 0
which try accomplish c code:
int main() { int i; (i = 0; < 5 && !fork(); i++) { printf("%d ", i); } wait(null); return 0; }
but prints
0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
and can't figure out how omit digits. can see what's wrong?
each iteration fork
s new child. parent exits loop , wait
s child, , child prints iteration number. however, because there no newline, characters remain buffered. however, each fork
duplicates buffer in current state. so, each child inherits of printed values ancestors, , waits child die before exiting. so, last child exits, buffers this:
parent: "" child-0 : "0 " child-1 : "0 1 " child-2 : "0 1 2 " child-3 : "0 1 2 3 " child-4 : "0 1 2 3 4 "
child-4 exits (because wait
not block), causing stdout
buffer flushed. causes child-3 return wait
, exits, causing stdout
buffer flushed. continues until parent exits, see following (all on 1 line because there no newlines anywhere):
0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
to fix this, flush buffer before printing. forces child's copy of parent's buffer output in sequence order, , children's own output appear exit in reverse order:
int main() { int i; (i = 0; < 5 && !fork(); i++) { fflush(stdout); printf("%d ", i); } wait(null); return 0; }
gives:
0 1 2 3 4 3 2 1 0
Comments
Post a Comment