Give the output for the following code. (Recall the wait () function pauses unti
ID: 3940629 • Letter: G
Question
Give the output for the following code. (Recall the wait () function pauses until any child process has completed. If a process does not have a child the function returns immediately.) With the wait (NULL) line commented out: With the wait (NULL) line not commented out: int main(void) {int i = 5, pid; printf("1:%d ", i); pid = fork(); i++; printf("2:%d ", i);//wait(NULL); if (pid == 0) {sleep(1); i--; printf("3:%d ", i); sleep(1); i += 4; printf("4:%d M, i);} else {i++; printf("5:%d ", i); i = i+3; printf("6:%d ", i); sleep (6); i = 0; printf("7:%d ", i);} i += 2; printf("8:%d ", i);Explanation / Answer
a) With the wait(NULL) line commented out:
Program:
#include <stdio.h>
int main(void)
{
int i=5,pid;
printf("1:%d ",i);
pid=fork();
i++;
printf("2:%d ",i);
//wait(NULL);
if(pid==0)
{
sleep(1);
i--;
printf("3:%d ",i);
sleep(1);
i+=4;
printf("4:%d ",i);
}
else
{
i++;
printf("5:%d ",i);
i=i+3;
printf("6:%d ",i);
sleep(6);
i=0;
printf("7:%d ",i);
}
i+=2;
printf("8:%d ",i);
}
Output:
1:5
2:6
3:5
4:9
8:11
1:5
2:6
5:7
6:10
7:0
8:2
b) With the wait(NULL) line not commented out:
Program:
int main(void)
{
int i=5,pid;
printf("1:%d ",i);
pid=fork();
i++;
printf("2:%d ",i);
wait(NULL);
if(pid==0)
{
sleep(1);
i--;
printf("3:%d ",i);
sleep(1);
i+=4;
printf("4:%d ",i);
}
else
{
i++;
printf("5:%d ",i);
i=i+3;
printf("6:%d ",i);
sleep(6);
i=0;
printf("7:%d ",i);
}
i+=2;
printf("8:%d ",i);
}
Output:
1:5
2:6
3:5
4:9
8:11
1:5
2:6
5:7
6:10
7:0
8:2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.