S
steve
I was given the following code, and asked what the possible outputs
could be. We're learning about processes and forking.
int value;
int main(){
int pid, number = 1;
value = 2;
pid = fork();
value = value + 2;
number = number + 2;
if (pid) {
printf(" 0 %d %d \n", value, number);
waitpid(pid, NULL, 0);
}
else{
printf(" 1 %d %d \n", value, number);
}
return 0;
}
I've come up with 3 possibilities so far; I don't know if any are
right:
1) the fork() fails; the parent's pid is assigned a negative integer,
so the if() condition passes and the output is 0 4 3
2) the fork() succeeds, the child* (pid = 0 from successful fork())
prints 1 4 3 and then returns; the parent (pid = child's process id #)
starts up prints 0 4 3 and returns
3) the fork() succeeds, but the child's quantum expires^ before it
reaches the printf(), the parent (pid = child's process id #) starts,
prints 0 4 3 and then waits for the child; the child (pid = 0 from
successful fork()) starts back up and prints 1 4 3 and returns; the
parent returns
* I guess the child takes precedence over the parent (system
dependent?) because every time I've run the program the output has been
1 4 3 followed by 0 4 3.
^ I guess the CPU's quantum length would have to be incredibly small
for case 3 to happen, but it's possible, right?
I'm new to this material, so any comments would be truly appreciated.
could be. We're learning about processes and forking.
int value;
int main(){
int pid, number = 1;
value = 2;
pid = fork();
value = value + 2;
number = number + 2;
if (pid) {
printf(" 0 %d %d \n", value, number);
waitpid(pid, NULL, 0);
}
else{
printf(" 1 %d %d \n", value, number);
}
return 0;
}
I've come up with 3 possibilities so far; I don't know if any are
right:
1) the fork() fails; the parent's pid is assigned a negative integer,
so the if() condition passes and the output is 0 4 3
2) the fork() succeeds, the child* (pid = 0 from successful fork())
prints 1 4 3 and then returns; the parent (pid = child's process id #)
starts up prints 0 4 3 and returns
3) the fork() succeeds, but the child's quantum expires^ before it
reaches the printf(), the parent (pid = child's process id #) starts,
prints 0 4 3 and then waits for the child; the child (pid = 0 from
successful fork()) starts back up and prints 1 4 3 and returns; the
parent returns
* I guess the child takes precedence over the parent (system
dependent?) because every time I've run the program the output has been
1 4 3 followed by 0 4 3.
^ I guess the CPU's quantum length would have to be incredibly small
for case 3 to happen, but it's possible, right?
I'm new to this material, so any comments would be truly appreciated.