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?
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?
Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.
Another Solution is to use write + sprintf
e.g.
char s[10];
sprintf(s,"four is %d",4);
write(STDOUT_FILENO,s,sizeof(s));
If printf() goes to a terminal, it is line buffered by default. Simply printing "1\n" and "2\n" would solve your problem.