Reputation:
This is my little program:
#include <unistd.h>
#include <stdio.h>
int main() {
printf("1");
fork();
printf("2");
fork();
return 0;
}
The output of this code is 12121212
and I ask:
Why does it print more than 122
?
Upvotes: 2
Views: 541
Reputation: 12619
If printf()
goes to a terminal, it is line buffered by default. Simply printing "1\n"
and "2\n"
would solve your problem.
Upvotes: 0
Reputation: 1
Another Solution is to use write + sprintf
e.g.
char s[10];
sprintf(s,"four is %d",4);
write(STDOUT_FILENO,s,sizeof(s));
Upvotes: 0
Reputation: 439
Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.
Upvotes: 6