What is the output of the following two programs? //Program 1 main () {int val =
ID: 3799041 • Letter: W
Question
What is the output of the following two programs?
//Program 1 main () {int val = 5; if(fork() > 0){wait{$val); val - WEXITSTATUS(val);} val++; printf("%d ", val); return val;}//Program 2 main() {int val = 5; if (for3?() > 0) {wait($val); val = EXITSTATUS(val);} else exit(val); val++; printf("%d ", val); return val;} Here is a description of the return value of wait() from the corresponding UNIX manpage: RETURN VALUES When wait () returns due to a terminated child process, the process ID of the child is returned to the calling process. Otherwise, -1 is returned and error is set to indicate the error. ERRORS The wait() function will fail if: ECHILD The calling process has no existing unwaited-for child processes.Explanation / Answer
//program1 output
6
7
if parent process is given time slice for execution, there is a wait system call , so parent parent process waits for child to exit. So child process is given time to execute , which increaments the val and prints the value 6 .Aftr printing , child exit and parent process wakes up . Here WEXITSTATUS in parent returns the value 6 .In parent process ,there is increament for val ie 6 becomes 7 and print the val as 7 and parent exits.
----------------------------
//output of program2
6
I think there is mistake here in this EXITSTATUS, it gives compilation error , hope this is same as for program1 ie
WEXITSTATUS. I assume this and proceed to explain.
Here fork() > 0 means if it is parent process , then parent process waits for child process as wait system call is executed in parent. In else part , ie if child process , child exits with state as val , means value of val ie 5 is returned to parent process as exit status of child and child exits. After child exists, parent wakes up and in the parent process it increaments the val and prints it as 6 ( val will be 5 after executing WEXITSTATUS in parent process ), so that val will be icnreamented and parent process prints 6. There will be only one value printed on screen.
//output
6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.