Can anyone explain why this fork execution prints my text 8 times?

I can’t understand why it prints text 8 times. In my concept, it should print only 2 times. Can anyone help me out?

The code:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    pid_t x=0;
    pid_t y=0;
    x=fork();
    if(y>0)
        fork();
    if(x==0)
        y=fork();
    fork();
    if(y==0){
        fork();
        printf("Some text\n");
    }
}
+4
source share
2 answers

x = fork(); 2 processes are in progress.

if (y>0) fork(); will never be executed.

if (x==0) y=fork();will be executed by the child process, so now 3 processes are running. For the original parent y, still 0. For this child y == child_child pid, and for the child child - y==0.

All 3 processes will be executed fork(), therefore only 6 processes, of which 4 have y==0in their memory.

4 fork , 8 , printf(...);

+4

, . ​​

#include <stdio.h>
#include <stdlib.h>
#include "unistd.h"
int main() {
    pid_t x=0;
    pid_t y=0;

    printf("FORK X \n");
    x=fork();

    if(y>0) {
        printf("FORK 1 \n");
        fork();
    }

    if(x==0) {
        printf("FORK 2 \n");
        y=fork();
    }

    printf("FORK 3 \n");
    fork();
    if(y==0){
        printf("FORK 4 \n");
        fork();
        printf("Some text\n");
    }
}

, "FORK 4" TWO "Some text", :

: tmp 52 $./a.out

FORK X 
FORK 3 
FORK 4 
FORK 2 
FORK 4 
Some text
Some text
FORK 3 
FORK 3 
Some text
Some text
FORK 4 
Some text
FORK 4 
Some text
Some text
Some text

4 "FORK 4" ( fork() A B):

  • @x = fork() → x!= 0 @FORK 3 fork A
  • @x = fork() → x!= 0 @FORK 3 fork B
  • @x = fork() → x = 0 @y = fork() → y = 0 @FORK 3 fork A
  • @x = fork() → x = 0 @y = fork() → y = 0 @FORK 3 fork B

@x = fork() → x = 0 @y = fork() → y!= 0 " ".

FORK X --------> x != 0 -------------------------------> FORK 3 A -----> FORK 4 A (Some text)
          |              |                                          |--> FORK 4 B (Some text)
          |              |
          |              |-----------------------------> FORK 3 B -----> FORK 4 A (Some text)
          |                                                         |--> FORK 4 B (Some text)
          |
          |
          |----> x == 0 -----> FORK 2 A ( y = 0 ) -----> FORK 3 A -----> FORK 4 A (Some text)
                         |                                          |--> FORK 4 B (Some text)
                         |                         |---> FORK 3 B -----> FORK 4 A (Some text)
                         |                                          |--> FORK 4 B (Some text)
                         |
                         |---> FORK 2 B (y != 0 ) -----> FORK 3 A -----> XXX bad end
                                                   |---> FORK 3 B -----> XXX bad end
+1

Source: https://habr.com/ru/post/1668466/


All Articles