Binary Process Tree using fork

Hello everyone,

I am trying create a 4-level binary process tree using fork(). This means one parent process spawns 2 children, which spawn 4 grandchildren (2 each), which spawn 8 great grandchildren (2 each). I cannot use pipes. So far I have managed to get 3 (slightly correct) levels. That is, 1 parent, 1 child, 2 grandchildren. I've been working one this for days, please help. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
main()
{ 
  int stat;
  int returnPid;
  int i;
  
  returnPid = fork();

  if (returnPid == -1) 
  {
     perror("can't fork"); exit(1);
  }
  
		else if (returnPid == 0)
		{  // Child 
             
		  for (i=0; i<2; i++)
		  {
		  		 
		    if ((returnPid = fork()) == 0)
		    { // GrandChild
		    
		    
		      printf("GrandChild: child pid = % d, my pid = %d, parent pid = %d \n",
                          returnPid, getpid(), getppid());
		      exit(0);
     		    }
              }
		
		 wait();
            
		 printf("Child: child pid = % d, my pid = %d, parent pid = %d \n",
                          returnPid, getpid(), getppid());
		
             exit(0);
            
            }
     
		else 
		{  // Parent 
          		 
		  wait();
		
		  printf("Parent: child pid = %d, my pid = %d, parent pid = %d \n ",
                          returnPid, getpid(), getppid(0));
                   
		  exit(0);
            }
}



Here's my output:


GrandChild: child pid = 0, my pid = 5748, parent pid = 8524
Child: child pid = 5992, my pid = 8524, parent pid = 540
GrandChild: child pid = 0, my pid = 5992, parent pid = 8524
Parent: child pid = 8524, my pid = 540, parent pid = 3852
Write
1
2
3
4
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h> 


Then you'll get some compilation errors that might prevent you from rude mistakes.

Be aware that function wait() waits for only one (any) child to terminate.
Topic archived. No new replies allowed.