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 ;)