Say that we have a global variable int a = 0
, how many times will a
be printed, and what's the first and end value?
for(int i=0; i<6; i++){
fork();
a++;
printf("a = %d\n", a)
}
printf("a = %d\n", a);
Here's what I did:
and so far I have 2+4+8+16+32=62
in side of the loop, and all of the processes reach the outside loop for extra 32 so I get 94
prints in total with a=1
first value and a=62
end value.
I would appreciate any feedback about my solution, as of I'm not sure how to test it in code since I can't use fork in windows.
Thanks in advance!
Once fixed and completed as described below, the program prints either 190 or 448 lines in common conditions, depending on where its standard output is directed.
First, the program will not print anything because printf("a = %d\n", a)
does not have a semicolon after it, so the program will not compile and hence will not execute.
Let’s assume we add the missing semicolon, include <stdio.h>
and <unistd.h>
, wrap the code in a main
routine, and compile and execute in a Unix environment. Then, in the case where the output is going to an interactive device:
printf
format strings end with \n
.) Each line will be sent to the device as soon as it is sent to the output stream. So it will be sent before the following fork
.i
, in iteration 0, one process becomes two, a
is incremented from 0 to 1 (separately in each process), and each process prints “a = 1”. So two “a = 1” lines are printed.a
becomes 2, and four “a = 2” are printed.a
is 6, and 64 “a = 6” are printed.If output is going to a file on disk or to a pipe, it is fully buffered. Let’s assume the buffer is large enough to hold all the output from one process. In this case:
a
is incremented from 0 to 1, and each process prints “a = 1” into its buffer. Now each buffer holds “a = 1”.If the lines printed were longer, or there were more of them per process, they could fill the buffer at times, and the processes would print their lines early. Those lines would then not be duplicated by later forks, and the total printed would be somewhere between the minimum (from line buffered output) to the maximum (from fully buffered output that completely fits in the buffer). We could also get fragmented lines due to line endings not coinciding with filling the buffer.