C fork () processes

I am learning the concept of parent process and child processes on UNIX. I wrote this little code, thinking that x is not. or processes will be created. But he created a different number -

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argv, char *argc[])
{
    int i;
    pid_t childpid;

    for(i=0; i<3; i++)
    {
        childpid = fork();
        if(childpid == -1)
        {
            perror("Failed to Fork");
            return 1;
        }

        if(childpid == 0)
            printf("You are in Child: %ld\n", (long)getpid());
        else
            printf("You are in Parent: %ld\n", (long)getpid());
    }
    return 0;
}

OUTPUT:
You are in Parent: 30410
You are in Child: 30411
You are in Parent: 30410
You are in Child: 30412
You are in Parent: 30411
You are in Parent: 30410
You are in Child: 30413
You are in Child: 30414
You are in Parent: 30412
You are in Parent: 30411
You are in Child: 30415
You are in Child: 30416
You are in Parent: 30413
You are in Child: 30417

I understand that in a situation, a fork()parent or child may have a preference for execution. This does not bother me, I am worried about the number of processes that are running. Why is it 14? and not some 2 ^ n number, which would be if we did fork(); fork(); fork()ie fork one by one.

What am I missing?

UPDATE: Another clarification -

The function forkcopies the parent image of the memory so that the new process receives a copy of the address space of the parent.

What does it mean? Does it mean -

  • Does the child process start after the instruction fork()?
  • ? x=3 fork, x 3?
+3
5

8 , , - .

:

You are in Parent: 30410
You are in Parent: 30410
You are in Parent: 30410

You are in Parent: 30411
You are in Parent: 30411
You are in Child: 30411

You are in Parent: 30412
You are in Child: 30412

You are in Parent: 30413
You are in Child: 30413

You are in Child: 30414

You are in Child: 30415

You are in Child: 30416

You are in Child: 30417

, 8 .

. () , . "", , , PID (), PID ( ) ( ).

, 0, i == 0 . i == 1. i == 2. .

, .

      ____A____
     /    |    \
    B_    C_    D
    | \     \
    E  F     G
     \
      H

/, | \ , i - 0, 1 2 .

, ( E), , i == 1 fork i == 2. , |, \.

, B, / (i == 0), fork | (i == 1) \ (i == 2).

fork, . , Linux .

+12

fork(), , . ,

i = 0, 2
i = 1, 4
i = 2, 8

rlibby , , . . :

i = 0, 1 + 1 ( 2)
i = 1, 2 + 2 ( 4)
i = 2, 4 + 4 ( 8)

+2

, , , , , fork , for. , , , , .

, , :

if(childpid == 0) {
    printf("You are in Child: %ld\n", (long)getpid());
    exit(0);
}

, , 2 n , n . , . , , n 2 n.

, !

+1

There are only 8 processes. Count unique process identifiers.

+1
source

I think adding a break instead of adding exit (0) will also work.

0
source

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


All Articles