I try to create a process tree as in the first screenshot. My code is not working correctly. The result of my code is shown in the second screenshot. The problem is that I do not know how to create the latest generation of processes. enter image description here enter image description here

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main() { int i; int j; pid_t ppid; pid_t cpid; ppid = getpid(); printf("I'm the parent, my PID is: %d\n", ppid); for (i = 0; i < 4; i++) { ppid = fork(); if (ppid == 0) { printf("Hello, my PID is: %d, my parent's PID is %d\n", getpid(), getppid()); for(j = 0; j < 2; j++) { ppid = fork(); if (ppid == 0) { printf("Hello, my PID is: %d, my parent's PID is %d\n", getpid(), getppid()); sleep(60); printf("I'm process %d and I'm done\n", getpid()); exit(0); } } sleep(60); printf("I'm process %d and I'm done\n", getpid()); exit(0); } } sleep(1); printf("I'm process %d. Waiting for one of my children to complete", getpid()); wait(NULL); printf("Eltern: I'm done\n"); printf("... and bye. \n"); } 
  • Do you understand how fork() works? - PinkTux

1 answer 1

I think you need to add the third generation of threads just. For each stream from the second generation (of which two are created in a loop), you need to call fork again inside. Where the result is fork == 0, insert the code for the stream from the last level, otherwise, put the code for the stream in the second level.

  for(j = 0; j < 2; j++) { ppid = fork(); if (ppid == 0) { //child 1..2 ppid=fork(); if (ppid==0) { // child 1..1 потоки с последнего 3 уровня выполнят этот код printf("Hello, my PID is: %d, my parent's PID is %d\n",getpid(),getppid()); sleep(60); printf("I'm process %d and I'm done\n", getpid()); exit(0); } else { // а этот код выполнят потоки втрого уровня printf("Hello, my PID is: %d, my parent's PID is %d\n", getpid(), getppid()); sleep(60); printf("I'm process %d and I'm done\n", getpid()); exit(0); } } } 
  • Can I have a passing question? How to make each parent process wait for all child processes to end? wait (null) waits for the end of any child, but not all. - Evhenii Vasylenko
  • one
    The search suggests that you can call wait (null) more than once, for example, in a loop, until the result is an ECHILD, for example: while ((wait (NULL)! = ECHILD) {sleep (1)}; Found here [ stackoverflow.com/a/23872806/5521474] - Ivan Ts