Home > OS >  How do I make it so that processes are created parallel to each other rather than one after another?
How do I make it so that processes are created parallel to each other rather than one after another?

Time:06-04

I need help in modifying this code. Right now, it creates a process, and then waits for its termination. After which, another process is created, and then it waits for its termination. I want to modify it so that it creates both processes at the same time and executes them parallel to each other. The code is:

#include <sys/types.h>
#include <stdio.h>
int main(int argc, char * argv[]) {
  pid_t pid;
  int status;
  pid = fork();
  if (pid != 0) {
    while (pid != wait( & status));
  } else {
    sleep(5);
    exit(5);
  }
  pid = fork();
  if (pid != 0) {
    while (pid != wait( & status));
  } else {
    sleep(1);
    exit(1);
  }
}

CodePudding user response:

Here's code that should do the job:

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

int main(void)
{
  pid_t pid = fork();
  if (pid != 0)
    printf("Child 1 PID = %d\n", pid);
  else
  {
    sleep(5);
    exit(5);
  }
  pid = fork();
  if (pid != 0)
  {
    printf("Child 2 PID = %d\n", pid);
    int corpse;
    int status;
    while ((corpse = wait(&status)) > 0)
        printf("Child %d exited with status 0x%.4X\n", corpse, status);
  }
  else
  {
    sleep(1);
    exit(1);
  }
  return 0;
}

One time when I ran it, I got the output:

Child 1 PID = 49582
Child 2 PID = 49583
Child 49583 exited with status 0x0100
Child 49582 exited with status 0x0500

If you preferred, you could move the wait() loop and its variable declarations after the if structures and immediately before the return 0; at the end. That would give you better symmetry. You could even wrap up the child creation phase into a function called twice:

static void procreate(int kidnum, int naptime)
{
    int pid = fork();
    if (pid != 0)
        printf("Child %d PID = %d (nap time = %d)\n", kidnum, pid, naptime);
    else
    {
        sleep(naptime);
        exit(naptime);
    }
}

and then in main() you'd just have two calls to procreate() and the wait loop:

int main(void)
{
    procreate(1, 5);
    procreate(2, 1);

    int corpse;
    int status;
    while ((corpse = wait(&status)) > 0)
        printf("Child PID %d exited with status 0x%.4X\n", corpse, status);
    return 0;
}
  • Related