views:

45

answers:

2

We had a school exercise today to create multiple processes. Our problem was not the code itself neither the understanding of fork().

The problem me and my mate had were why it didn't create 4 processes of our code as shown below:

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>

//kod

int child1();
int child2();

int main() {

        pid_t pid1, pid2;
        int i;

        pid1 = fork();
        pid2 = fork();

        if(!pid1)
                child1();
        else if(!pid2)
                child2();
        else {
                printf("parentlolololololol");
        }

        for(;;)

        return 0;
}
int child1(){
        for(;;) {
                printf("A");
                fflush(stdout);
                sleep(1);
        }
        return 0;
}

int child2(){
        for(;;){
                printf("B");
                fflush(stdout);
                sleep(1);
        }
        return 0;
}

We have a sliced discussion whether the program creates 4 processes or not. Do the second fork()-call create a new process of the child and why isn't it being held up by any loop if that case? Or doesn't the second fork()-call create a new process of the child at all?

This is not relevant to our exercise in any way, but we're very curious, as you have to be as a programmer ;)

A: 

The issue is the missing semicolon on this line:

    for(;;)

    return 0;

This means that the main program will return 0 forever - actually only effective the first time.

After the first fork there are two processes, one where pid1 is 0 and one where it is not. Each of these two processes then calls the second fork statement - two of them will have pid2 == 0 and two not.

main ---> fork --> pid1 == 0 --> fork --> pid2 == 0
                                      --> pid2 != 0
               --> pid1 != 0 --> fork --> pid2 == 0
                                      --> pid2 != 0

So there are 4 processes. Entering the conditionals, two are caught by 'child1' and one is caught by 'child2'. The main process exits. That leaves 3 processes running, two printing 'A' and one printing 'B'.

sje397
oh lol, thanks for the quick reply. We understand the problem now and it created 3 processes and as the parent ended, the process count is exact.
nattefrost
A: 

It does - it forks twice unconditionally, creating 4 processes (well, 3 new ones anyway). Two of them should run child1(), one child2() and one the parent code. This is because you have 4 different values for the pid1/pid2 pair, and the first if covers two of them.

aib