Manage forks in C

I have a C file that looks like this:

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
int main () 
{ 
    pid_t child_pid; 
    printf ("The PID is %d\n", (int) getpid ()); 
    child_pid = fork (); 
    if (child_pid != 0)
    { 
        printf ("this is the parent process, with PID %d\n", 
        (int)getpid()); 
        printf ("the child PID is %d\n", (int) child_pid); 
    } 
    else 
        printf ("this is the child process, with PID %d\n", 
        (int)getpid()); 
    return 0; 
} 

I need to modify it to create a hierarchy that looks like

parent (0)
  |
  +---> child (1)
  |
  +---> child (2)
          |
          +----> child (3)
          |
          +----> child (4)
                  |
                  +----> child (5)
                  |

Basically a tree structure, where every second child creates two new children. As far as I understand, when I am a fork()process, each process will be launched simultaneously. Adding fork()to the statement ifseems to work and correctly creates processes 0 through 2, since only the parent will create a new fork. But I have no idea how to make process 2 a fork, not 1. Any ideas?

+3
source share
4 answers

, 1 . 2 fork if-statement. , 2 fork , fork-if, 0.

:

if(fork) {
    // Inside process 0
    if(fork) {
        // still in process 0
    } else {
        // in process 2
        if(fork) {
          // still in process 2
        } else {
          // in prcess 3
        }
        // and so on
    }
} else {
    // Inside process 1
}
+2

.

, , ( , ).

+2

, , fork. . fork() for, .

, fork() - , . vfork , , .

+2

, . fork() , :

PID , 0 . -1 , , errno .

, , fork() 0 , :

int main()
{
   // Here we're in the parent (0) process

   if(fork())  // This starts the chain, only the parent will do this
    if(!fork()) //the child will pass this, the parent will skip it
     for(count = 0; counter < number_of_processes; counter++) //now the 2nd child loops
     {
         if(fork())
             if(!fork());
         else
             break;
     }

:

//parent (18402)
if(fork()) // spawns 18403, parent 18402 keeps going
  if(!fork()) // spawns 18404, parent 18402 drops to the end of main()
    for(count = 0; count < number_of_processes; conter++) // 18404 enters here
      if(fork())  // 18404 forks 18405 and then goes on
        if(!fork());  // 18404 spawns 18406 before leaving, 18406 restarts the loop
        else
          break; // 18404 breaks out there
      else
          break; //18405 leaves the loop here

, :

  18402
    |
    +---> 18403
    |
    +---> 18404
            |
            +----> 18405
            |
            +----> 18406
                     |

, , , .

+1

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


All Articles