ballstowall
ballstowall

Reputation: 55

How do I better implement functions like wait to control the order in which my created processes run?

I just read about the wait function in my textbook, however, I'm having a hard time implementing it to control the order of my processes. The outcome here is as follows: Child ID: 141 Grandchild ID: 142 Dad ID: 140

I'd like to switch the grandchild line with the childline. Any recommended resources to learn about this desired type of control? The posted learning material barely goes over this, despite asking me to do an assignment entirely based on creating multiple processes and requesting a specific order to their execution and output.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) {
  
  int pid;
  int pid2;
  pid = fork();
  
int aids;

  wait(NULL);

  switch(pid)
  {
    case -1:
      printf("Error: Not able to fork process");
      break;
    case 0:
      
      printf("Child ID:      %d \n", getpid());
     
      pid2 = fork();
      if(pid2==0) printf("Grandchild ID: %d\n", getpid());

      else if(pid2 != -1) wait(NULL); // wait for grandchild
      break;
    default:
   
      printf("Dad ID:        %d \n",getpid() );
      break;
  }
  //printf("Hello World    %d\n", getpid());
  return 0;
}

Upvotes: 0

Views: 53

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754100

As I noted in a comment, you simply need to print the child ID after you know the grandchild has exited, which is when the wait() returns in the child process:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    int pid = fork();
    int pid2;

    wait(NULL);

    switch (pid)
    {
    case -1:
        fprintf(stderr, "Error: Not able to fork process\n");
        break;

    case 0:
        pid2 = fork();
        if (pid2 == 0)
            printf("Grandchild ID: %d\n", getpid());
        else if (pid2 != -1)
        {
            wait(NULL);               // wait for grandchild
            printf("Child ID:      %d\n", getpid());
        }
        break;

    default:
        printf("Dad ID:        %d\n", getpid());
        break;
    }
    return 0;
}

Sample output (source file gk29.c, executable gk29):

$ gk29
Grandchild ID: 65860
Child ID:      65859 
Dad ID:        65858 
$ gk29
Grandchild ID: 65863
Child ID:      65862 
Dad ID:        65861 
$

Upvotes: 1

Related Questions