Question: ( 4 0 points ) Simple C programs on fork ( ) . Suppose all printf ( ) will be followed by fflush ( stdout

(40 points) Simple C programs on fork(). Suppose all printf() will be
followed by fflush(stdout) even if it is not presented in the code. For all the
C programs, you can assume that necessary header files are included
(5 points) Consider the following code segments:
int main()
{
pid_t pid1;
pid_t pid2;
pid1= fork();
pid2= fork();
printf("pid1:%d, pid2:%d
", pid1, pid2);
}
(a) How many processes are there in total when this code finishes?
Give the answer.
(b) If one process prints "pid1:51234, pid2: 51235", one process prints
"pid1:0, pid2: 51236", write down other processes' pid and their
outputs.
(15 points) Consider the following code segments:
int main(){
int i =0;
int cnt =10;
for (; i3; i++){
pid_t pid = fork();
if (pid ==0)
printf("%d
", cnt);
else
cnt +=10;
}
return 0;
}
(a) Who will print the "cnt", the child process or parent process? Why?
How many times of "printf" will this code execute? Give the answer
with explanation.
(b) Theoretically, based on Linux fork() mechanism introduced in the
lecture, how many memory copies of the variable "cnt" will there
be? Explain your answer.
(c) Directly running this piece of code may produce different outputs
every time. Briefly explain why.
( 4 0 points ) Simple C programs on fork ( ) .

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!