Consult the fork problem

Have a interview questions, asked to print the number"-"
#include <stdio.h>
#include <unistd.h>

int main(void){
int i;

for(i=0;i<2;i++){
fork();
printf("-\n");
}
return 0;
}

Fork it is returned in two, was 2 at the time of printing is 6, the 3 time for 14 months, I have not quite understand, please master answer, I thanked first


If I put printf in the next line, is the other. Why? The younger brother Xianxie
#include <stdio.h>
#include <unistd.h>

int main(void){
int i;

for(i=0;i<2;i++){
fork();
printf("-");
}
   printf("\n");
return 0;
}

Started by Christine at February 10, 2016 - 12:13 AM

This is normal ah, fork 1 is divided into 2, the first loop, each process output a '-', then the two processes fork again, into 4 processes, each of the output of a '-'; 2+4 =6; i=3, 2+4+8 = 14.

The output of the following answer a different reason, because the printf ("-"); buffer statements, and no real output, the fork, the cache is copied to the child process space, therefore, have more than two, to 8, not 6.

Posted by Tiffany at February 15, 2016 - 12:40 AM

Or some fuzzy, thank you so much!
#include <unistd.h>

void f1(){
int i;
pid_t pid;

for(i=0;i<4;i++){
if((pid=fork())<0)
printf("fork error!\n");
else if(pid == 0){
printf("- ");
}else
printf("* ");
}
}

int main(void){

f1();
printf("\n");
return 0;

}

Answer:

* * * *
* * * -
* - * -
* - * *
* - - *
* - - -
* * - *
- - * *
- - * -
- - - *
- - - -
- * * *
- * - *
- * - -
* * - -
coco@linux-cycv:~/coco/coco> - * * -

2^4*4 has such a rule
2^The number of n= line, and then take the n is equal to the number.
2^N * n is equal to the number of print out

Posted by Christine at March 02, 2016 - 1:24 AM

Well, actually there is a study is the \n. What do you feel.

Posted by Tiffany at March 09, 2016 - 1:40 AM

Thank you so late to help answer version

Posted by Christine at March 10, 2016 - 2:26 AM

A buffer, the default is line buffered terminal. If a pipe to the cat output, the results would also be affected

Posted by Horace at January 03, 2017 - 10:48 PM

This involves a number of fork problems, you draw a process diagram (a tree) is clear.

BTW, Fork returns only once, but in the process of returning once.

Posted by Chapman at January 06, 2017 - 11:33 PM

In 1, fork stepfather into sub process will print. The second time cycle process and create a child process. So it is 6
2: Printf terminal with the buffer, the parent process printf, the data is placed in the buffer, and did not immediately display, and then go to the fork data will be
Also a copy, so not the same.

Posted by Fiona at January 08, 2017 - 11:02 PM