Saturday, April 7, 2018

Fork and Wait Example

Here is a little experimental programming.  Forked two processes and caught those processes.


 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
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main()
{
 pid_t child_pid1,child_pid2;
 
 printf ("This is the print before Fork\n");
 child_pid1=fork();
 
 if (child_pid1 == 0) {
  //This is Child 1
  printf("\tCHILD1 >> pid=%d----parentpid=%d\n",getpid(),getppid());
 
  printf("\tCHILD1 >> Child 1 is sleeping\n");
  sleep(10);
  printf("\tCHILD1 >> Child 1 wokeup and is terminated\n\n");
 } else {
  child_pid2=fork();
  if (child_pid2 == 0) {
   //This is Child 2
   printf("\tCHILD2 >> pid=%d----parentpid=%d\n",getpid(),getppid());

   printf("\tCHILD2 >> child 2 is sleeping\n");
   sleep(3);
   printf("\tCHILD2 >> Child 2 wokeup and is terminated\n\n");
  } else {
   //This is parent
   int status=0,ret;
   printf("Waiting for any Child to terminate\n");
   ret = wait(&status);
   printf("Caught first one %d\n\n",ret);

   printf("Waiting for any Child to terminate\n");
   ret = wait(&status);
   printf("Caught second one %d\n\n",ret);

   printf("Waiting for any Child to terminate\n");
   ret = wait(&status);
   printf("Caught third one %d\n",ret);
  }
 }
}

We forked two processes,
  • Child 1 will sleep for 10 secs
  • Child 2 will sleep for 3 secs
  • Child 2 will exit before Child 1
  • 2 Wait commands to catch watever child exists first
  • A wait more to see what happens if there are no more childs left
The output of the program is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
root@kali:/media/root/persistence# ./a.out
This is the print before Fork
Waiting for any Child to terminate
 CHILD1 >> pid=2835----parentpid=2834
 CHILD1 >> Child 1 is sleeping
 CHILD2 >> pid=2836----parentpid=2834
 CHILD2 >> child 2 is sleeping
 CHILD2 >> Child 2 wokeup and is terminated

Caught first one 2836

Waiting for any Child to terminate
 CHILD1 >> Child 1 wokeup and is terminated

Caught second one 2835

Waiting for any Child to terminate
Caught third one -1

The second child, child2 (2836) will exit first.  Then the first child, child1(2385) will exit next.  The third wait, as it had no child to wait for returns -1.



No comments:

Post a Comment