Shawn Liu Shawn Liu - 13 days ago 5
Linux Question

I want to know what the different between is two way create child process in Linux with fork()?

I want to create 2 child process and 1 parent process with fork()

The first method:

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void){
pid_t b,c;
printf("a");

if(0 == ( b = fork())){
printf("b");
}
if(0 == ( c = fork())){
printf("c");
}
return 0;
}


The second method:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argv,char ** argc){
pid_t fpid1,fpid2;
fpid1 = fork();
if(fpid1 == 0){
printf("b");
}else{
fpid2 = fork();
if( fpid2 == 0){
printf("c");

}else{
printf("a");

}
}
return 0;
}


After run these code,i found the answer is different
The first is

a
b
c


The second is
random

i forgot add fpid2 = fork(); sorry!!
please help me

Answer

The first program forks twice, but the second one - only once, so that fpid_2 is left unititialized, hence the undefined behavior (the randomness you're talking about).

Comments