Reputation: 1
I need to create "n" child processes and they have to sleep a random number of seconds, and the parent process have to advise when any child process has finished. The problem is that each child process runs one after other and I need them to work in parallel. (In the code I'm just creating 3 children.)
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(void)
{
pid_t pid;
int x,zeit,status,w,n=0;
for(x=1;x<=3;x++)
{
pid=fork();
n++;
srand(time(NULL));
if(pid)
{
w=wait(&status);
printf("Process %d finished in %d seconds (Dad:%d cuenta %d)\n",w,WEXITSTATUS(status),getppid(),n);
}
else
{
int n;
zeit=rand()%3+1;
sleep(zeit);
exit(zeit);
}
}
exit(0);
return 0;
}
Upvotes: 0
Views: 2357
Reputation: 31204
You're explicitly waiting for each process to finish before you start the next one
for(x=1;x<=3;x++)
{
pid=fork();
n++;
srand(time(NULL));
if(pid)
{
w=wait(&status);
printf("Process %d finished in %d seconds (Dad:%d cuenta %d)\n",
w, WEXITSTATUS(status), getppid(), n);
...
}
If you want them to run in parallel, you're going to have to make 3 different processes, and start them off before you wait for any one of them to finish.
Upvotes: 2