Thursday, April 12, 2018

waitpid waiting for pids to terminate

Last time, we used 'wait' to wait for any forked process to finish.  Now, using waitpid we can dictate what process to catch.   Here's the code:


 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 starts sleeping\n");
  sleep(10);
  printf("\tCHILD1 >> Child 1 stops sleeping\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 starts sleeping\n");
   sleep(3);
   printf("\tCHILD2 >> Child 2 stops sleeping\n");
  } else {
   //This is parent
   int status=0,ret;
   printf("Waiting for any Child to terminate\n");
   ret = waitpid(child_pid1,&status,0);
   printf("Caught first one %d with status %d\n\n",ret,status);

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

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

When the program is executed, after the following lines are print there will be a pause

root@kali:/media/root/persistence# ./a.out 
This is the print before Fork
Waiting for any Child to terminate
 CHILD1 >> pid=3196----parentpid=3195
 CHILD2 >> pid=3197----parentpid=3195
 CHILD1 >> Child 1 starts sleeping
 CHILD2 >> child 2 starts sleeping

Then the pause after the following line:

CHILD2 >> Child 2 stops sleeping

Then rest of the lines follows

 CHILD1 >> Child 1 stops sleeping
Caught first one 3205 with status 0

Waiting for any Child to terminate
Caught second one 3206 with status 0

Waiting for any Child to terminate
Caught third one -1

'Caught first one.......'. This line is executed as a result of wait_pid function call, in which we entered child_pid1 as the first argument.  I am ignoring the second and third arguments to reduce the complexity of understanding.  Even though child2 stops earlier than child1, as we mentioned specifically child_pid1 in wait_pid this happened.

The second wait_pid had child_pid2.  By the time, the program started executing this line, the second process has already been terminated.  So without any delay, things continued.

No comments:

Post a Comment