LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   fork (https://www.linuxquestions.org/questions/programming-9/fork-219890/)

beginner_84 08-19-2004 05:56 PM

fork
 
how to create multiple child process and make parent process wait till all child procesas have exitted
Code:

if(fork()==0)
..
else if(fork()==0)
........
...............
.................
else wait();

doesnt work

ToniT 08-19-2004 06:23 PM

Code:

int pids[27];
int i=0;
for(i=0;i<27;i++) {
  if((pids[i]=fork())!=0) {
  } else {
    printf("Hi, I'm child number %d\n", i);
    break;
  }
}
// Now the parent has started 27 childs.
// At this point, i contains values 0..27, inclusive. 0-26 with the childs
// 27 is the parent.
switch(i) {
  case 0: ....
    ... //Whatever the childs do..
  case 26:
  case 27:
    { int j;   
      for(j=0;j<27;j++) waitpid(pids[i],NULL,0);
    }
}


Kumar 08-20-2004 04:53 AM

Hi,
This is one way I could think of -
Code:

#include <stdio.h>
#include <pthread.h>
#include <stdio.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>



pid_t pid;


pthread_t t1, t2;

void *
workthread (void *arg)
{
  pid = fork ();

  if (pid == 0)
    {
      fprintf (stderr, "\nchild pid : %d  and it's parent is %d\n", getpid (),
              getppid ());
      sleep (5);
    }
}

int
main ()
{
  int i = 0;

  for (i = 0; i < 5; ++i)
    {
      pthread_create (&t2, NULL, &workthread, NULL);
    }
  for (i = 0; i < 5; ++i)
    {
      pid = wait (NULL);
      fprintf (stderr, "\nchild %d terminated", pid);
    }
  return 0;
}

The code can be changed a bit if you want every child to perform different functions.


All times are GMT -5. The time now is 01:31 AM.