I have problems with understanding the behavior of this code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int nr;
nr = fork();
if (nr == 0) {
/* Child process */
printf("Child process, fork return value %dn", nr);
exit(0);
} else {
/* Parent process */
printf("Parent process, fork return value: %dn", nr);
exit(0);
}
}
When running in a Unix shell I get this result:
Parent process, fork return value: 343
Child process, fork return value: 0
But sometimes its only giving me this result without any shell prompt:
Child process, fork return value: 0
I know it can be solved with wait() function in parent process. But I like to know:
Why is result irregular? Could someone please explain what happening? Child process becomes a zombie, but why do not parents process printf() function call run?
Advertisement
Answer
There are 2 issuse to concider: 1) there is stdout buffering that you might want to flush
fflush(stdout);
2) multitasking can sometimes execute the stuff in an unexpected order I get something like this when that happens:
/tmp$ ./a.out
Parent process, fork return value: 24049
/tmp$ Child process, fork return value 0
as you can see the prompt is in the beginning of the child process output, it’s not missing altogether it’s just not where you expect it to be.
With this code I tried several times bit never had the prompt in teh output lines of the child or parent:
#include <stdio.h>
#include <stdlib.h>
int main() {
int nr;
nr = fork();
if (nr == 0) {
/* Child process */
printf("Child process, fork return value %dn", nr);
fflush(stdout);
exit(0);
} else {
/* Parent process */
printf("Parent process, fork return value: %dn", nr);
fflush(stdout);
sleep(1);
exit(0);
}
}