Brydon Gibson
Brydon Gibson

Reputation: 1307

Handling multiple fork()s in c

I'm struggling to understand this concept. Let's say I want to run 3 concurrent processes (threads are not an option, this is an assignment).

I would do:

int main(){
    fork();
    if (getPid() == -1) { //this is the parent
        fork(); //make a third process
    } else if (getPid() == 0) { //child process
    //do child things
    }

So from what I've learned the parent pid is -1. And there's two children, both with PID 0?

So then the "parent" can spawn as many children as possible, correct? They will all do child things.

What if I want to do 3 different things? How do I track the PID's so that I have 3 unique ones?

as per the comments - is this how it's done?

pid_t child2Pid;
pid_t child1Pid = fork();
switch /*if getPid is wrong what do I put here?*/ {
case -1: //parent
    child2Pid = fork(); //create another child
case child1Pid :
    //do what child1 would do
case child2Pid :
    //do what child2 would do

Upvotes: 1

Views: 1482

Answers (3)

blitz
blitz

Reputation: 9

int main()
{
pid_t pid;
int i;
for(i = 0;i < 3;i++)
{
    pid = fork();
}

if(pid == 0)
{
    printf("child\n");        
}
else if(pid > 0)
{
    printf("parent\n");
}

return 0;
}

you can use pid_t = fork() to record the value,and select what you do by the value.**

Upvotes: -1

Seva Alekseyev
Seva Alekseyev

Reputation: 61370

The whole idea is that you enter fork() once, but leave it twice - once in the parent, once in the child. In the parent, fork() returns the child's PID, in the child, fork() returns 0. -1 means error and there is no child.

So when you call fork(), look at the return value. Like this:

  if(fork() > 0) //We're in the parent, and a child was spawned
      fork(); //Spawn another.

This will create three processes. Error handling omitted.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182761

pid_t child1, child2, child3;
if ((child1 = fork()) == 0)
{
    // first child stuff goes here
    _exit(0);
}
if ((child2 = fork()) == 0)
{
    // second child stuff goes here
    _exit(0);
}
if ((child3 = fork()) == 0)
{
    // third child stuff goes here
    _exit(0);
}
// we are in the parent, we have the PIDs of our three
// children in child1, child2, and child3

Upvotes: 5

Related Questions