Brydon Gibson Brydon Gibson - 1 month ago 7
C Question

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

Answer
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
Comments