Necrode
Necrode

Reputation: 51

Spawn multiple children processes

So I want to spawn a number of children processes equal to a value inputted from the command line. I have all the values and everything reading in just fine, I just need to figure out how to spawn these children, and have them all call the same program.

Here is what I have so far:

for(int i = 0; i < processes; i++)
{
    pid = fork();
    printf("%d\n", pid);
}

if(pid < 0)
{
perror("fork");
exit(-1);

}

else if(pid == 0)
{

    /*for(int j = 0; j <= 5; j++)
    {
        execl("~/cs370/PA2/gambler.c","run", NULL);
        Gamble(percent);
    }*/

}

So to be clear again. I want to spawn "processes" amount of children, that all call "gambler.c". But ONLY 5 can be running at a time. It should wait(), and then process the rest of the children 5 at a time.

Sample input:

run -p 60 10

Where -p is a percentage to be fed to gambler.c which just returns success or failure based on a random number generator. 60 is the percentage. 10 is the number of processes.

Any help is much appreciated thanks!

Upvotes: 0

Views: 3092

Answers (1)

mjr
mjr

Reputation: 2113

Have you looked into the exec family? Exec will spawn processes. You can then use wait to monitor the processes. fork will give you the PID and you can then have a second thread loop over each pid calling wait and keeping track of each active process.

wait man page

exec man page

pid_t pid = fork()
if (pID == 0)
{
     //child
     //immediatly call whichever exec you need.  Do not do anything else.
     //do not log a message or print a string.  Any calls to c++ standard strings
     //will risk deadlocking you.
}
else if (pid < 0)
{
   //error
} 
else
{
   //parent.  store pid for monitoring
}

Upvotes: 1

Related Questions