#include "csapp.h"
int main()
{
int i;
for (i = 0; i < 2; i++)
fork();
printf("hellon");
exit(0);
}
/*
* .------------------------
* |
* |
* |
* .-----------.------------------------
* |
* |
* | .------------------------
* | |
* | |
* | |
* .-----------.------------------------
* fork fork
* i=0 i=1
*/
In the process pic, it seems the code will print “hello” four times.
Why print ‘hello’ three times in my centos?
2
Answers
Maybe a fork failed or there is a conflict among the
printf
. On ideone it correctly prints 4 times.Unless there’s something weird in your
csapp.h
header, you should be getting four lines printed out because after the first iteration of the loop (i == 0
before the increment), thefork()
creates two processes, and on the second iteration (i == 1
before the increment), each of those two processes executesfork()
to create two more processes.When this code is run on macOS 10.14.6, I get 4 lines saying
hello
:Output:
I’d instrument it far more than the bare minimal code shown in the question, though — like this:
Note the copious use of
fflush()
to avoid theprintf()
anomaly afterfork()
.An example output I got from this was:
Note that two of the processes reported
PPID = 1
because the parent process (5039) had already exited. It would be feasible/sensible to add a loop to wait for children to die and report their exit statuses.What do you get on CentOS?
I’m running the program from the command line in a terminal window. If you’re running this from an IDE or something, you might be losing the output from the orphaned processes. Adding the
wait()
loop would prevent the first process from exiting until all (both) its children had exited, leading to an orderly display of the 4 “Hello” lines. I’ve reworked the output formatting so it is easier to read the output.Sample output (no orphaned processes):