Hi there I am trying to create this process tree but I still confused whether DABC is possible to be printed or not
void main(){
/*
creating this process tree:
P1
/ \
P2 P3
*/
if(fork()){
if(fork()){
printf("A\n");
wait(NULL);
printf("B\n");
}
else{
printf("C\n");
}
}
else{
printf("D\n");
}
}
CodePudding user response:
Yes, it's possible.
In fact, all of the following outcomes are possible:
- ACBD
- ACDB
- ADBC
- ADCB
- CABD
- CADB
- CDAB
- DABC
- DACB
- DCAB
This can be visualized by stretching/shrinking a combination of light grey boxes.
There's one condition: One of the child processes must end before the statement after the wait
in P1. This is because wait
waits for a child — any child — to end.
Note that you can use waitpid
to wait for a specific process to end.
CodePudding user response:
I take the intent of the exercise to be that you should assume that all function calls complete successfully, that all processes involved terminate normally, and that the return of the wait()
call can be relied upon to indicate the termination of a child process, as opposed to its temporary stoppage via a signal. Subject to those assumptions and otherwise considering all allowed sequences of execution, you should recognize that the order of the output is governed by these constraints, and these alone:
- "A" and "B" will be printed in that relative order because that's the program order of a single process.
- At least one of "C" and "D" will be printed before "B" because the
wait()
ensures that one of the child processes (each of which prints one of those letters) finishes before "B" is printed.
"DABC" is among the many sequences consistent with those constraints, so yes, in principle, it is a possible output of the program presented. Whether that is a likely output is an altogether different question, whose answer depends on various characteristics of the C implementation and its operating environment.
If you make fewer of the assumptions enumerated above then that only increases the possible outputs, so the order "DABC" being possible does not depend on those assumptions.