Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading